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

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

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

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
        // write code here
        // 递归实现,终止条件
        if(root==null){
            return -1;
        }
        if(root.val==o1){
            return o1;
        }
        if(root.val==o2) return o2;

// 开始递归
        // 左子树右子树的最近公共祖先,也相当于找一棵树的最近公共祖先
        int left = lowestCommonAncestor(root.left,o1,o2);
        int right = lowestCommonAncestor(root.right,o1,o2);
        //如果左子树没有找到
        if(left==-1){
            return right;
        }
        if(right==-1){
            return left;
        }
        // 如果都没找到(也就是说两个节点不是在同一边)就是当前根节点(不一定是原树根节点)
        return root.val;
    }
}

全部评论

相关推荐

09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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