236.Lowest Common Ancestor of a BinaryTree

时间:2019-03-15
本文章向大家介绍236.Lowest Common Ancestor of a BinaryTree,主要包括236.Lowest Common Ancestor of a BinaryTree使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

给定一个二叉树和所要查找的两个节点,找到两个节点的最近公共父亲节点(LCA)。比如,节点5和1的LCA是3,节点5和4的LCA是5。

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) 
            return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);//如果p在左子树,则会返回p,否则返回空
        TreeNode right = lowestCommonAncestor(root.right, p, q);//如果q在右子树,则会返回q,否则返回空
        if(left != null && right != null){
            return root;//如果左右都不为空,则root肯定是祖先节点
        }
        return left == null ? right : left;
    }
}