网站主页作品欣赏,网站开发验收资料,微信商城怎么做,wordpress com org把二叉搜索树转换为累加树
力扣题目链接
题目描述
给出二叉 搜索 树的根节点#xff0c;该树的节点值各不相同#xff0c;请你将其转换为累加树#xff08;Greater Sum Tree#xff09;#xff0c;使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
提…把二叉搜索树转换为累加树
力扣题目链接
题目描述
给出二叉 搜索 树的根节点该树的节点值各不相同请你将其转换为累加树Greater Sum Tree使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
提醒一下二叉搜索树满足下列约束条件
节点的左子树仅包含键 小于 节点键的节点。 节点的右子树仅包含键 大于 节点键的节点。 左右子树也必须是二叉搜索树。
解题思路
利用两个栈来回倒腾一个栈完成二叉树的中序遍历另一个把遍历序列记录下来然后正好满足这个累加树的定义把值依次加上即可。
题解
class Solution {
public:TreeNode* convertBST(TreeNode* root) {if (!root) {return nullptr;}stackTreeNode* st;TreeNode* cur root;stackTreeNode* 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;}
};