Sunday, September 3, 2017

235. Lowest Common Ancestor of a Binary Search Tree

Solution 1. Use property of binary search tree. (Don't forget to use the conditions of the problem!)
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(p->val < root->val && q->val < root->val)
            return lowestCommonAncestor(root->left, p, q);
        if(p->val > root->val && q->val > root->val)
            return lowestCommonAncestor(root->right, p, q);
        return root;
    }
Solution 2. Property of binary tree not used.
    int preOrder(TreeNode* node, const TreeNode* p, const TreeNode* q, TreeNode*& res) {
        if(!node || res) return 0;
        int n = 0;
        if(node == p || node == q) n = 1;
        n += preOrder(node->left, p, q, res);
        if(n == 2 && !res) res = node;
        n += preOrder(node->right, p, q, res);
        if(n == 2 && !res) res = node;
        return n;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        TreeNode* res = nullptr;
        preOrder(root, p, q, res);
        return res;
    }

No comments:

Post a Comment