LeetCode 236. Lowest Common Ancestor of a Binary 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;
    }
};

 

你可能感兴趣的:(LeetCode)