2Sum on BST

这个题出现在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;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值