题目:
538. 把二叉搜索树转换为累加树
1038. 把二叉搜索树转换为累加树
题解:逆中序深度优先遍历
1. 题解一:递归法
2. 题解二:迭代法
代码:逆中序深度优先遍历
1. 代码一:递归法
public class code538 {
// 方法1: 递归法
public int sum = 0;
public TreeNode convertBST(TreeNode root)
{
if(root == null)
{
return null;
}
convertBST(root.right);
sum = sum + root.val;
root.val = sum;
convertBST(root.left);
return root;
}
public static void main(String[] args) {
Integer nums[] = { 5, 2, 13 };
TreeNode root = ConstructTree.constructTree(nums);
TreeOperation.show(root);
System.out.println("***************************************");
code538 test = new code538();
TreeNode res = test.convertBST(root);
TreeOperation.show(res);
}
}
2. 代码二:迭代法
import java.util.*;
public class code538 {
// 方法2: 迭代法
public TreeNode convertBST(TreeNode root)
{
int sum = 0;
TreeNode node = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
while(!stack.isEmpty() || node != null)
{
while(node != null)
{
stack.push(node);
node = node.right;
}
node = stack.pop();
sum = sum + node.val;
node.val = sum;
node = node.left;
}
return root;
}
public static void main(String[] args) {
Integer nums[] = { 5, 2, 13 };
TreeNode root = ConstructTree.constructTree(nums);
TreeOperation.show(root);
System.out.println("***************************************");
code538 test = new code538();
TreeNode res = test.convertBST(root);
TreeOperation.show(res);
}
}