236. Lowest Common Ancestor of a Binary Tree

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        if (root == p || root == q) return root;
        
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        
        if (left != null && right != null) return root;
        
        return left == null ? right : left;
    }
236. Lowest Common Ancestor of a Binary Tree236. Lowest Common Ancestor of a Binary Tree 宇智波爱编程 发布了225 篇原创文章 · 获赞 43 · 访问量 9万+ 私信 关注
上一篇:235. Lowest Common Ancestor of a Binary Search Tree (E)


下一篇:LeetCode236. Lowest Common Ancestor of a Binary Tree(二叉树的最近公共祖先)