- Binary Search Tree to Greater Sum Tree
根据题目给出的例子,相当于要做一个reverse sort,由于得到sorted array的是inorder traversal,就把inorder sort反过来实现。
- Binary Search Tree to Greater Sum Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode bstToGst(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
// push every subtree in inorder traversal to the stack
// traversal the tree in reverse of inorder traversal
// right root left
int val = 0;
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.right;
}
cur = stack.pop();
cur.val = cur.val + val;
val = cur.val;
cur = cur.left;
}
return root;
}
}
recursion 版本
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int val = 0;
public TreeNode bstToGst(TreeNode root) {
if (root == null) {
return root;
}
if (root.right != null) {
bstToGst(root.right);
}
root.val = val + root.val;
val = root.val;
if (root.left != null) {
bstToGst(root.left);
}
return root;
}
}
- Two Sum BSTs
其中一个pointer放在tree的最小值依次增大,另一个pointer放在另一个tree的最大值,依次减小
- Two Sum BSTs
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean twoSumBSTs(TreeNode root1, TreeNode root2, int target) {
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
while (true) {
while (root1 != null) {
stack1.push(root1);
root1 = root1.left;
}
while (root2 != null) {
stack2.push(root2);
root2 = root2.right;
}
if (stack1.isEmpty() || stack2.isEmpty()) {
break;
}
TreeNode t1 = stack1.peek();
TreeNode t2 = stack2.peek();
if (t1.val + t2.val == target) {
return true;
} else if (t1.val + t2.val < target) {
stack1.pop();
root1 = t1.right;
} else {
stack2.pop();
root2 = t2.left;
}
}
return false;
}
}