[leetcode]235. Lowest Common Ancestor of a Binary Search Tree

[leetcode]235. Lowest Common Ancestor of a Binary Search Tree


Analysis

厉害的人总是那么的厉害呀~—— [菜鸡反省中~]

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
寻找二叉树中两个节点的最早共同祖先。

Implement

/**
 * 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) {
        while(root != p && root != q){
            if(p->val <= root->val && q->val <= root->val)
                root = root->left;
            else if(p->val >= root->val && q->val >= root->val)
                root = root->right;
            else
                break;
        }
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/80680179