题目说明
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
分析
直接看到题目会想到利用中序遍历,进行累加,得到最终的总和后,再利用中序遍历进行减去前面节点的和赋值给当前节点的运算,这样也可以得到最终的结果。最后参考别人的代码时,知道了可以对中序遍历进行逆操作,也即是左根右变为右根左。
写非递归算法时,注意中序遍历要利用栈来存储~
代码
// 递归版本
// class Solution {
// public:
// int node = 0;
// TreeNode* convertBST(TreeNode* root) {
// if(!root) return NULL;
// convertBST(root->right);
// root->val += node;
// node = root->val;
// convertBST(root->left);
// return root;
// }
// };
// 非递归版本
class Solution {
public:
int node = 0;
TreeNode* convertBST(TreeNode* root) {
if(!root) return NULL;
stack<TreeNode*> tr;
TreeNode *p = root;
//检查栈是否为空,以及栈中p指针是否有指向
while( !tr.empty() || p ) {
//先右遍历到最右节点,先将根存入栈,再存右孩子,弹出元素时实现先右节点后根的遍历
while(p) {
tr.push(p);
p = p->right;
}
//将指针移到栈头
p = tr.top();
//已经赋值给p,将栈头元素弹出
tr.pop();
//执行操作
p->val += node;
node = p->val;
p = p->left;
}
//由于p是指向root的指针,因此对p所做的操作会改变root,最后直接返回root
return root;
}
};