LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 时间复杂度(O( logn))

时间复杂度(O( logn))

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==NULL||root->val==p->val||root->val==q->val) return root;
        TreeNode* node_left  = lowestCommonAncestor(root->left ,p,q);
        TreeNode* node_right = lowestCommonAncestor(root->right,p,q);        
        if(node_right==NULL) return node_left;
        if(node_left==NULL ) return node_right;
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/ziyue246/article/details/81393705