zoukankan      html  css  js  c++  java
  • LN : leetcode 538 Convert BST to Greater Tree

    lc 538 Convert BST to Greater Tree


    538 Convert BST to Greater Tree

    Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

    Example:

    Input: The root of a Binary Search Tree like this:
                  5
                /   
               2     13
    
    Output: The root of a Greater Tree like this:
                 18
                /   
              20     13
    

    递归 Accepted

    二叉搜索树的特点是对于任一节点来说,其左子树结点都比其小,其右子树结点都比其大。所以对于本题,只需利用递归,先访问最右结点,以一个sum值记录从大到小的原数值和。

    /**
    * Definition for a binary tree node.
    * struct TreeNode {
    *     int val;
    *     TreeNode *left;
    *     TreeNode *right;
    *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    * };
    */
    class Solution {
    public:
        int sum = 0;
        TreeNode* convertBST(TreeNode* root) {
            travel(root);
            return root;
        }
        void travel(TreeNode* root) {
            if (!root)  return;
            if (root->right)    travel(root->right);
            root->val = (sum += root->val);
            if (root->left)    travel(root->left);
        }
    };
    
  • 相关阅读:
    第04组 Beta冲刺 (2/5)
    第04组 Beta冲刺 (1/6)
    第04组 Alpha冲刺 总结
    二叉树的递归与非递归
    各类典例模板
    选择题合辑2
    运算符重载
    链表题目
    集合的模拟实现(类模板)
    2018Final静态成员(黑名单)
  • 原文地址:https://www.cnblogs.com/renleimlj/p/7715800.html
Copyright © 2011-2022 走看看