• 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


    将一棵二叉搜索树变成一棵更大的二叉搜索树


    C++(40ms):
     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) 
     8  * };
     9  */
    10 class Solution {
    11 private:
    12     int sum = 0 ;
    13 public:
    14     void travel(TreeNode* root){
    15         if (!root)
    16             return ;
    17         if (root->right)
    18             travel(root->right) ;
    19         sum += root->val ;
    20         root->val = sum ;
    21         if (root->left)
    22             travel(root->left) ;
    23     }
    24     
    25     TreeNode* convertBST(TreeNode* root) {
    26         travel(root) ;
    27         return root ;
    28     }
    29 };
  • 相关阅读:
    4-1 软件原型设计
    3-1 案例分析
    2-1 编程作业
    1-2阅读任务
    1-1 准备工作
    第十周学习总结
    实验报告2&&第四周课程总结
    Java实验报告(一)&&第三周学习总结
    第三周编程总结
    2019年春季学期第二周作业
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8574279.html
Copyright © 2020-2023  润新知