0%

538. 把二叉搜索树转换为累加树

538. 把二叉搜索树转换为累加树

中序遍历变种
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
int rightVal = 0;
dfs(root, rightVal);
return root;
}
private:
void dfs(TreeNode* root, int& rightVal)
{
if(!root)
return;
if(root->right)
{
dfs(root->right, rightVal);
}
root->val += rightVal;
rightVal = root->val;
if(root->left)
{
dfs(root->left, rightVal);
}
}
};

右->中->左

rightVal始终保存他右边树枝的最大值

我好傻

简单的思考方法:

中序单增,于是反中序为单减,对于每个节点加上他左边的和就行

迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
stack<TreeNode*> q;
int curSum = 0;
TreeNode* ret = root;
while(!q.empty() || root)
{
while(root)
{
q.push(root);
root = root->right;
}
root = q.top();
q.pop();
curSum += root->val;
root->val = curSum;
root = root->left;
}
return ret;
}
};