版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/85837345
给定二叉搜索树(BST),将其转换为更大的树,使原始BST上每个节点的值都更改为在原始树中大于等于该节点值的节点值之和(包括该节点)。
样例
Given a binary search Tree `{5,2,13}`:
5
/ \
2 13
Return the root of new tree
18
/ \
20 13
解题思路1:
先右子树再根节点再左子树的形式递归,其中设置全局变量sum用来累加节点和。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the root of binary tree
* @return: the new root
*/
public TreeNode convertBST(TreeNode root) {
// write your code here
dfs(root);
return root;
}
private int sum = 0;
private void dfs(TreeNode root){
if(root == null)
return;
dfs(root.right);
sum += root.val;
root.val = sum;
dfs(root.left);
}
}
解题思路2:
非递归方式。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the root of binary tree
* @return: the new root
*/
public TreeNode convertBST(TreeNode root) {
// write your code here
if(root == null)
return null;
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
int sum = 0;
while(node != null || !stack.isEmpty()){
while(node != null){
stack.push(node);
node = node.right;
}
node = stack.pop();
sum += node.val;
node.val = sum;
node = node.left;
}
return root;
}
}