二叉树的最近公共祖先

 (1) 递归:

写一个函数:判断以root为根节点的子树中是否含有p和q节点

有两种情况:p q分别在左右子树上;

                        p q在同一个子树上,此时root节点是其中一个

利用回溯特性,root是深度最深的公共节点

private TreeNode ans;


    public boolean dfs(TreeNode root, TreeNode p, TreeNode q){
        if(root == null) return false;
        boolean lson = dfs(root.left, p, q);
        boolean rson = dfs(root.right, p, q);
        if((lson && rson) || ((root.val == p.val || root.val == q.val) && (lson || rson)) ){
            this.ans = root;
        
        }
        return lson || rson || root.val == p.val ||  root.val == q.val;

    }


    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root, p, q);
        return this.ans; 
    }

时间 O(N)

空间O(n)

(2)存储路径

HashMap<Integer, TreeNode> mapFather = new HashMap<Integer, TreeNode>();
    Set<Integer> visited = new HashSet<Integer>();


    public void dfs(TreeNode root){
        if(root.left != null){
            mapFather.put(root.left.val, root);
            dfs(root.left);
        }
        if(root.right != null){
            mapFather.put(root.right.val, root);
            dfs(root.right);
        }
    }


    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root);
        while(p != null){
            visited.add(p.val);
            p = mapFather.get(p.val);
        }

        while(q != null){
            if(visited.contains(q.val)){
                return q;
            }
            q = mapFather.get(q.val);
        }
        return root;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值