1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
class Solution {
public boolean findTarget(TreeNode root, int k) { Deque<TreeNode> leftStack = new ArrayDeque<>(), rightStack = new ArrayDeque<>(); TreeNode temp = root; while (temp != null) { leftStack.push(temp); temp = temp.left; } temp = root; while (temp != null) { rightStack.push(temp); temp = temp.right; } TreeNode left = leftStack.peek(), right = rightStack.peek(); while (left.val < right.val) { int sum = left.val + right.val; if (sum < k) left = getNext(leftStack, true); else if (sum > k) right = getNext(rightStack, false); else return true; } return false; }
private TreeNode getNext(Deque<TreeNode> stack, boolean isLeft) { TreeNode node = isLeft ? stack.pop().right : stack.pop().left; while (node != null) { stack.push(node); node = isLeft ? node.left : node.right; } return stack.peek(); } }
|