LeetCode - 236. Lowest Common Ancestor of a Binary Tree

本文介绍了两种查找二叉树中两个指定结点的最低公共祖先的方法:递归法和迭代法。递归法通过递归左右子树来确定公共祖先,而迭代法则通过追踪结点的父结点来实现。

Binary Tree的问题,首先要考虑使用递归的思想:如果当前的结点为空或为目标结点之一,那么就直接返回当前结点,接下来递归地在左右子树中寻找目标结点,如果两个目标结点分别在root的两侧,那么root就是它们的lowest common ancestor;如果left为空,那么说明两个目标结点都在right子树中,返回right;反之则返回left。代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left != null && right != null) return root;
        return left != null? left : right;
    }
}


第二种方法是迭代,比较容易理解,分别记录p和q结点之前(包括p和q)的每个节点的parent,然后我们使用一个Set存储p结点的所有parent,然后逐步寻找q结点的所有parent,如果Set里面已经有这个元素,那么就直接返回。代码如下:

public class Solution{
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
        Map<TreeNode, TreeNode> parent = new HashMap<>();
        Stack<TreeNode> stack = new Stack<>();
        
        parent.put(root, null);
        stack.push(root);

        while(!parent.containsKey(p) || !parent.containsKey(q)){
            TreeNode node = stack.pop();
            if(node.left != null){
                parent.put(node.left, node);
                stack.push(node.left);
            }
            if(node.right != null){
                parent.put(node.right, node);
                stack.push(node.right);
            }
        }

        Set<TreeNode> ancestors = new HashSet<>();
        while(p != null){
            ancestors.add(p);
            p = parent.get(p);
        }
        while(!ancestors.contains(q)){
            q = parent.get(q);
        }
        return q;
    }
}


知识点:

1. 注意第二种迭代法中寻找每个node parent结点的方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值