题解这么少,我来写一个

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

http://www.nowcoder.com/questionTerminal/e0cc33a83afe4530bcec46eba3325116

import java.util.*;
//map保存所有节点的<子节点,父节点>,通过遍历将o1的所有父节点保存在list中
//然后遍历o2及其父节点,如果list的父节点中含有,则返回,即为最近的共同祖先
//list中保存了o1及其所有祖先节点,保存o1自身是为了情况:o2的父节点是o1(即同一侧)
public class Solution {
    HashMap<Integer,Integer> hm = new HashMap<>();
    public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
        if(root.val==o1||root.val==o2) return root.val;
        ArrayList<Integer> list = new ArrayList<>();
        recur(root);
        //添加o1,因为有可能包含(o2的父节点是o1)的情况
        list.add(o1);
        //通过遍历,list保存了o1的所有祖先
        while(hm.get(o1)!=null){
            list.add(hm.get(o1));
            o1 = hm.get(o1);
        }
        //如果o2是o1的祖先路径上的某点,直接返回o2即为祖先
        if(list.contains(o2)) return o2;
        //遍历o2的祖先,找出最近的公共祖先
        while(hm.get(o2)!=null){
            o2 = hm.get(o2);
            if(list.contains(o2)) return o2;
        }
        return -1;
    }

    void recur(TreeNode root){
        if(root.left!=null){
            hm.put(root.left.val,root.val);
            recur(root.left);
        }
        if(root.right!=null){
            hm.put(root.right.val,root.val);
            recur(root.right);
        }
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务