思路
方法一:就是暴力的计算每个节点要替换的值,一次存入list中,然后再遍历list,将二叉树的值替换。
方法二;
因为是二叉搜索数,所以其要加的值就是其右孩子的所有值+其父节点的右孩子的所有值。
所以其递归顺序是右中左,反中序遍历。
代码
方法一:
/**
* 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 {
public TreeNode convertBST(TreeNode root) {
if(root == null){
return root;
}
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
List<Integer> res = new ArrayList<Integer>();
while(stack.size() != 0){
TreeNode node = stack.pop();
res.add(fun(root,node.val,0));
if(node.right != null){
stack.push(node.right);
}
if(node.left != null){
stack.push(node.left);
}
}
int index = 0;
stack.push(root);
while(stack.size() != 0){
TreeNode node = stack.pop();
node.val = res.get(index++);
if(node.right != null){
stack.push(node.right);
}
if(node.left != null){
stack.push(node.left);
}
}
return root;
}
public int fun(TreeNode root,int val,int sum){
if(root == null){
return sum;
}
if(root.val>=val){
sum+=root.val;
}
sum = fun(root.left,val,sum);
sum = fun(root.right,val,sum);
return sum;
}
}
方法二:
/**
* 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 {
int sum;
public TreeNode convertBST(TreeNode root) {
if(root == null){
return root;
}
sum = 0;
convertBST1(root);
return root;
}
// 按右中左顺序遍历,累加即可
public void convertBST1(TreeNode root) {
if (root == null) {
return;
}
convertBST1(root.right);
sum += root.val;
root.val = sum;
convertBST1(root.left);
}
}
|