LeetCode 236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.


The problem will get interesting if the tree node has parent node. (....need to be continued)


TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root) return NULL;
        if(root == p || root == q) return root;
        TreeNode* tmp_1 = lowestCommonAncestor(root->left, p, q);
        TreeNode* tmp_2 = lowestCommonAncestor(root->right, p, q);
        if(tmp_1 && tmp_2) return root;
        return tmp_1 ? tmp_1 : tmp_2;
    }


你可能感兴趣的:(LeetCode 236. Lowest Common Ancestor of a Binary Tree)