538. Convert BST to Greater Tree

 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 static int wing=[]()
11 {
12     std::ios::sync_with_stdio(false);
13     cin.tie(NULL);
14     return 0;
15 }();
16 
17 class Solution 
18 {
19 public:
20     TreeNode* convertBST(TreeNode* root) 
21     {
22         stack<TreeNode*> s;
23         TreeNode *p=root;
24         int sum=0;
25         while(p||!s.empty())
26         {
27             if(p)
28             {
29                 s.push(p);
30                 p=p->right;
31             }
32             else
33             {
34                 p=s.top();
35                 p->val=p->val+sum;
36                 sum=p->val;
37                 s.pop();
38                 p=p->left;
39             }
40         }
41         return root;
42     }
43 };

逆中序遍历,右根左。用的迭代,也可以用递归

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9134050.html