Leetcode 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

解题思路:按照题目意思,是从最右右子树开始累加sum,所以可以按照右子树 -> 中间节点 -> 左子树 这样的顺序去对这个二叉查找树进行累加节点数值。
 1 #include <stdio.h>
 2 
 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 void travel_tree(TreeNode *node, int &sum){
11     if (!node){
12         return;
13     }
14     travel_tree(node->right, sum);
15     sum += node->val;
16     node->val = sum;
17     travel_tree(node->left, sum);
18 }
19 
20 class Solution {
21 public:
22     TreeNode* convertBST(TreeNode *root) {
23         int sum = 0;
24         travel_tree(root, sum);
25         return root;
26     }
27 };
28 
29 void preorder_print(TreeNode *node, int layer){
30     if (!node){
31         return;
32     }
33     for (int i = 0; i < layer; i++){
34         printf("-----");
35     }
36     printf("[%d]\n", node->val);
37     preorder_print(node->left, layer + 1);
38     preorder_print(node->right, layer + 1);
39 }
40 
41 int main(){
42     TreeNode a(5);
43     TreeNode b(3);
44     TreeNode c(6);
45     TreeNode d(2);
46     TreeNode e(4);
47     TreeNode f(7);
48     a.left = &b;
49     a.right = &c;
50     b.left = &d;
51     b.right = &e;
52     c.right = &f;
53     Solution solve;
54     TreeNode *root = solve.convertBST(&a);
55     preorder_print(&a, 0);
56     return 0;
57 }

 

posted @ 2018-04-07 16:08  Hwangzhiyoung  阅读(200)  评论(0编辑  收藏  举报