文章目录
- 1. 题目
- 2. 逆中序(根右左,降序循环遍历)
1. 题目
给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
例如:输入: 二叉搜索树:5/ \2 13输出: 转换为累加树:18/ \20 13
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-bst-to-greater-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 逆中序(根右左,降序循环遍历)
- 循环
class Solution {
public:TreeNode* convertBST(TreeNode* root) {stack<TreeNode*> stk;int prevSum = 0;TreeNode* rootcopy = root;while(root || !stk.empty()){while(root){stk.push(root);root = root->right;}root = stk.top();prevSum += root->val;root->val = prevSum;root = root->left;stk.pop();}return rootcopy;}
};
- 递归
class Solution {int sum = 0;
public:TreeNode* convertBST(TreeNode* root) {if(!root) return NULL;convertBST(root->right);sum += root->val;root->val = sum;convertBST(root->left);return root;}
};