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

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

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;
    }
}

全部评论

相关推荐

12-15 19:41
已编辑
广东工业大学 前端工程师
smile丶snow:尽量保证的一张a4纸吧。为什么工作经历只有公司?如果项目经历是工作里面的,应该写到工作经历里的吧。没有写项目职责,项目全是一个人写的吗?标题大小也好怪。两个项目的分割看不出来是,它和那些项目成功字体是一样大的
点赞 评论 收藏
分享
12-27 22:36
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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