二叉查找树(BST):根节点大于等于左子树所有节点,小于等于右子树所有节点。
二叉查找树中序遍历有序。
给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node
的新值等于原树中大于或等于 node.val
的值之和。
提醒一下,二叉搜索树满足下列约束条件:
注意:本题和 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同
输入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
输出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
输入:root = [0,null,1]
输出:[1,null,1]
输入:root = [1,0,2]
输出:[3,3,2]
输入:root = [3,2,4,1]
输出:[7,9,4,10]
提示:
二叉搜索树中序遍历就是有序的,所以中序遍历该树,大于或等于 node.val
的值即是当前节点遍历值及其后面的值。
node.val
的值之和,所以采用右、中、左的遍历顺序,即可得到逆序的序列;sum
,记录已经遍历节点的和,当遍历到node
节点时,只需再加上sum
,即为该节点的替换值。法一:递归、法二:迭代
略,具体思路请看:94. 二叉树的中序遍历
法一:递归
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int sum = 0;
public TreeNode convertBST(TreeNode root) {
dfs(root);
return root;
}
public void dfs(TreeNode root){
if(root == null) return;
if(root.right != null) dfs(root.right);
root.val += sum;
sum = root.val;
if(root.left != null) dfs(root.left);
}
}
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sum = 0;
TreeNode* convertBST(TreeNode* root) {
dfs(root);
return root;
}
void dfs(TreeNode* root){
if(root == nullptr) return;
if(root->right != nullptr) dfs(root->right);
root->val += sum;
sum = root->val;
if(root->left != nullptr) dfs(root->left);
}
};
法二:迭代
Java
class Solution {
public TreeNode convertBST(TreeNode root) {
Stack<TreeNode> stk = new Stack();
int sum = 0;
if(root == null) return root;
TreeNode cur = root;
while(cur != null || !stk.isEmpty()){
while(cur != null){
stk.push(cur);
cur = cur.right;
}
cur = stk.pop();
cur.val += sum;
sum = cur.val;
cur = cur.left;
}
return root;
}
}
C++
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
stack<TreeNode*> stk;
int sum = 0;
if(root == nullptr) return root;
TreeNode* cur = root;
while(cur != nullptr || !stk.empty()){
while(cur != nullptr){
stk.push(cur);
cur = cur->right;
}
cur = stk.top();
stk.pop();
cur->val += sum;
sum = cur->val;
cur = cur->left;
}
return root;
}
};
n
是二叉搜索树的节点数。每一个节点恰好被遍历一次。题目来源:力扣。
放弃一件事很容易,每天能坚持一件事一定很酷,一起每日一题吧!
关注我 leetCode专栏,每日更新!