题解 | #在二叉树中找到两个节点的最近公共祖先#

在二叉树中找到两个节点的最近公共祖先

https://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */

    /**
     我们只要往上找,找到他们第一个相同的公共祖先节点即可,
     但怎么找到每个节点的父节点呢,我们只需要把每个节点都遍历一遍,
     然后顺便记录他们的父节点存储在Map中。
     */
    public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
        Map<Integer, Integer> map = new HashMap<>();
        Queue<TreeNode> que = new LinkedList<>();
        map.put(root.val, -1);
        que.add(root);
        // 只有两个节点都搜索到,才会停止遍历
        while (!map.containsKey(o1) || ! map.containsKey(o2)) {
            TreeNode ptr = que.poll();
            if (ptr.left != null) {
                que.add(ptr.left);
                map.put(ptr.left.val, ptr.val);
            }
            if (ptr.right != null) {
                que.add(ptr.right);
                map.put(ptr.right.val, ptr.val);
            }
        }
        Set<Integer> ancestor = new HashSet<>();
        while (map.containsKey(o1)) {
            ancestor.add(o1);
            o1 = map.get(o1);
        }

        while (!ancestor.contains(o2)) {
            o2 = map.get(o2);
        }
        return o2;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 17:17
点赞 评论 收藏
分享
机械打工仔:有说的你怀疑一下就行了,直接问也太实诚了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务