把二叉搜索树转换为累加树
力扣题目链接
题目描述
给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
提醒一下,二叉搜索树满足下列约束条件:
节点的左子树仅包含键 小于 节点键的节点。
节点的右子树仅包含键 大于 节点键的节点。
左右子树也必须是二叉搜索树。
解题思路
利用两个栈来回倒腾,一个栈完成二叉树的中序遍历,另一个把遍历序列记录下来,然后正好满足这个累加树的定义,把值依次加上即可。
题解
class Solution {
public:TreeNode* convertBST(TreeNode* root) {if (!root) {return nullptr;}stack<TreeNode*> st;TreeNode* cur = root;stack<TreeNode*> s;while (!st.empty() || cur != nullptr) {if (cur != nullptr) {st.push(cur);cur = cur->left;} else {cur = st.top();st.pop();s.push(cur);cur = cur->right;}}int num = 0;while (!s.empty()) {cur = s.top();s.pop();cur->val += num;num = cur->val;}return root;}
};