leetcode之Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:淘宝国际转运公司时效 编辑:程序博客网 时间:2024/04/29 18:03

题目:

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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

解答:

根据BST的特性,进行路径查找,第一个路径分歧点就是LCA

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        while(root)
        {
            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
                return root;
        }
    }
};

0 0
原创粉丝点击