Leetcode 538. Convert BST to Greater Tree

Posted Hwangzhiyoung

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

 

以上是关于Leetcode 538. Convert BST to Greater Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode:Convert BST to Greater Tree

538. Convert BST to Greater Tree 538.将BST转换为更大的树

538. Convert BST to Greater Tree

538. Convert BST to Greater Tree

538. Convert BST to Greater Tree

538. Convert BST to Greater Tree