码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 538. Convert BST to Greater Tree

时间:2018-04-07 17:34:35      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:image   travel   order   arch   input   etc   inpu   change   like   

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

标签:image   travel   order   arch   input   etc   inpu   change   like   

原文地址:https://www.cnblogs.com/Hwangzhiyoung/p/8733586.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!