clueless coding // TODO: be smarter

LeetCode Lowest Common Ancestor of a Binary Tree: Java Solution



TL;DR Code Solution


public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

    if (root == null) {
        return root;

    }

    if (root == p || root == q) {
        return root;
    }

    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);

    if (right != null && left != null) {
        return root;
    }

    else return left == null ? right : left;


}