Simple Accepted C++ Solution for Any Binary Tree


  • 0
    M
    class Solution {
    public:
        bool Exists(TreeNode * root, TreeNode * x) {
            if (!root) return false;
            if (root == x) return true;
            return Exists(root->left, x) || Exists(root->right, x);
        }
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if (root == p || root == q) return root;
            if (Exists(root->left, p) && Exists(root->left, q)) return lowestCommonAncestor(root->left, p, q);
            if (Exists(root->right, p) && Exists(root->right, q)) return lowestCommonAncestor(root->right, p, q);
            return root;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.