Leetcode 235 Solution

This article provides solution to leetcode question 235 (lowest-common-ancestor-of-a-binary-search-tree)

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree

Solution

/**
 * 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) {
        if (root == NULL)
            return NULL;

        int low_val = min(p->val, q->val);
        int high_val = max(p->val, q->val);

        while (root)
        {
            if (low_val <= root->val && root->val <= high_val)
                return root;

            if (root->val > high_val)
                root = root->left;

            if (root->val < low_val)
                root = root->right;
        }

        return NULL;
    }
};