这个题出现在zenefits的电面中过. 要求time: O(n), space:O(lgn).
先找到最左和最右node,然后同时开始非递归遍历。一个找后继,一个找前继
import java.util.Stack;
public class MJ {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode n1=new TreeNode(15);
TreeNode n2=new TreeNode(10);
TreeNode n3=new TreeNode(20);
TreeNode n4=new TreeNode(8);
TreeNode n5=new TreeNode(12);
TreeNode n6=new TreeNode(16);
TreeNode n7=new TreeNode(25);
n1.left=n2;n1.right=n3;
n2.left=n4;n2.right=n5;
n3.left=n6;n3.right=n7;
for(int i=18;i<=45;i++)MJ.findK(i, n1);
}
static boolean findK(int k, TreeNode root)
{
TreeNode left=root, right=root;
Stack<TreeNode> stack1=new Stack<TreeNode>(), stack2=new Stack<TreeNode>();
while(left!=null)
{
stack1.push(left);
left=left.left;
}
while(right!=null)
{
stack2.push(right);
right=right.right;
}
left=stack1.peek();
right=stack2.peek();
while(left.val <= right.val && left!=right)
{
if(left.val+right.val==k)
{
System.out.println(k+"="+left.val+"+"+right.val);
return true;
}
if(left.val+right.val<k)
{
stack1.pop();
if(left.right!=null)
{
left=left.right;
while(left!=null)
{
stack1.push(left);
left=left.left;
}
}
if(stack1.isEmpty())return false;
else left=stack1.peek();
}
else
{
stack2.pop();
if(right.left!=null)
{
right=right.left;
while(right!=null)
{
stack2.push(right);
right=right.right;
}
}
if(stack2.isEmpty())return false;
else right=stack2.peek();
}
}
return false;
}
}
class TreeNode
{
int val;
TreeNode left, right;
TreeNode(int x)
{
val=x;
left=right=null;
}
}