C++ Solution w/ helper function


  • 0
    C
        /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            TreeNode *lca=NULL;
            findLCA(root, p, q, lca);
            return lca;
        }
        
        bool findLCA(TreeNode *root, TreeNode *p, TreeNode *q, TreeNode* &lca) {
            if (!root)
                return false;
            bool l=findLCA(root->left, p, q, lca),
                 r=findLCA(root->right, p, q, lca);
            if (root == p || root == q) {
                if (l || r)
                    lca = root;
                return true;
            } else {
                if (l && r) {
                    lca = root;
                }
                return l || r ? true : false;
            }
        }
    };

  • 0
    T

    This always makes me smile: return l || r ? true : false;


Log in to reply
 

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