题目
给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
例如:
输入: 原始二叉搜索树:
5
/ \
2 13
输出: 转换为累加树:
18
/ \
20 13
注意:本题和 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-bst-to-greater-tree
解题思路
这道题目跟前面的题目相比没有新的知识点,二叉搜索树的概念在235.二叉搜索树的最近公共祖先里已经学习过了。
这道题目考察的是中序遍历的反向遍历
如上图的二叉搜索树
中序遍历的结果是:[0,2,3,4,5,6,7,8,9]
转换成累积二叉树的中序遍历结果是:[44,44,42,39,35,30,24,17,9]
从未累加的中序遍历结果可以看出,中序遍历的遍历是有序的,结果从小到大排列。
为了求累积二叉树,可以反向遍历,先遍历到最大值的结点,然后逐步累加。
代码(C++)
递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sum=0;
TreeNode* convertBST(TreeNode* root) {
if(root==NULL) return NULL;
convertBST(root->right);
sum+=root->val;
root->val=sum;
convertBST(root->left);
return root;
}
};
非递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
int sum=0;
stack<TreeNode*> st;
TreeNode* temp=root;
while(!st.empty()||temp){
while(temp){
st.push(temp);
temp=temp->right;
}
temp=st.top();
st.pop();
sum+=temp->val;
temp->val=sum;
temp=temp->left;
}
return root;
}
};