LCA

LeetCode 235

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

题目代码:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        TreeNode *cur = root;
        while (1) {
            if (p -> val < cur -> val && q -> val < cur -> val)
                cur = cur -> left;
            else if (p -> val > cur -> val && q -> val > cur -> val)
                cur = cur -> right;
            else
                break;
        }
        return cur;
    }
};

 

posted @ 2020-09-22 07:55  锤子科技未来产品经理  阅读(176)  评论(0)    收藏  举报