leetcode 235. Lowest Common Ancestor of a Binary Search Tree

知识点:

两个节点的最近公共祖先

思路:

用dfs从根节点往下搜索节点,用栈记录从根节点到该节点之间的所有节点。由于栈的先进后出特性,我们就能得到该节点到根节点的序列。

两个节点的最近公共祖先就是各自往上回溯祖先时的第一个相同的节点。
由于两个节点到公共祖先的距离不一样,所以两个栈的大小不一样。先计算栈大小的差值,然后将元素多的那个栈的节点先弹出几个节点。接下来两个栈的栈顶元素到公共祖先的距离就是一样了。两个栈同时弹出元素,直到找到共通祖先。


class Solution {

    private Stack<TreeNode> pPath=new Stack<>();
    private Stack<TreeNode> qPath=new Stack<>();
    public boolean dfs(TreeNode root,TreeNode t,Stack<TreeNode> s){

        if(root !=null){
            if(root.val ==t.val){
                return true;
            }else {
                s.push(root.left);
                if(dfs(root.left,t,s)) {
                    return true;
                }else {
                    s.pop();
                }
                s.push(root.right);
                if(dfs(root.right,t,s)){
                    return true;
                }else {
                    s.pop();
                }
                return false;
            }
        }

        return false;
    }
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        pPath.push(root );
        dfs(root,p,pPath);
        qPath.push(root );
        dfs(root,q,qPath);
        int h;
        if(pPath.size() > qPath.size()){
            h=pPath.size() - qPath.size();
            for(int i=0;i<h;++i){
                pPath.pop();
            }
        }else {
            h=qPath.size() - pPath.size();
            for(int i=0;i<h;++i){
                qPath.pop();
            }
        }
        h=qPath.size();
        TreeNode result = null;
        for(int i=0;i<h;++i){
            if(qPath.peek() == pPath.peek()){
                result= qPath.peek();
                break;
            }else {
                qPath.pop();
                pPath.pop();
            }
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值