538.把二叉搜索树转换为累加树
思路
首先是想到迭代法,反中序遍历,右中左,依次遍历修改值。
还有递归法,同样反中序遍历,递归修改每个节点的值。
题解mrriors算法遍历看不懂。
代码
迭代法
public TreeNode convertBST(TreeNode root) {
HashMap<Integer,Integer> sum=new HashMap<>();
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
int pre=Integer.MAX_VALUE;
while (cur!=null||!stack.isEmpty()){
if (cur!=null){
stack.push(cur);
cur=cur.right;
}else {
cur=stack.pop();
//记录每一个值及后置节点
if (pre==Integer.MAX_VALUE){//树最大值
sum.put(cur.val, cur.val);
}else {
sum.put(cur.val, cur.val+ pre);
cur.val=cur.val+ pre;
}
pre=cur.val;
cur=cur.left;
}
}
return root;
}
递归
int sum=0;
public TreeNode convertBST(TreeNode root) {
if (root==null) return null;
convertBST(root.right);
root.val=sum+root.val;
sum=root.val;
System.out.println(sum);
convertBST(root.left);
return root;
}