题解 | 妙策

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

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

public class Solution {

    public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
        return (LCA(root, o1, o2)).val;
    }
    
    public static TreeNode LCA(TreeNode root, int o1, int o2){
        if(root == null || root.val == o1 || root.val==o2){
            return root;
        }
        TreeNode left = LCA(root.left, o1, o2);
        TreeNode right = LCA(root.right, o1, o2);
        //如果左树和右树都不为空,则返回头部
        if(left != null && right != null){
            return root;
        }
        
        return left != null ? left : right;
    }
}

全部评论

相关推荐

见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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