- Leetcode-236Lowest Common Ancest
- [Leetcode]236. Lowest Common Anc
- 1143 Lowest Common Ancestor(30 分
- 236. Lowest Common Ancestor of a
- 236. Lowest Common Ancestor of a
- 236. Lowest Common Ancestor of a
- 236. Lowest Common Ancestor of a
- 236. Lowest Common Ancestor of a
- 236. Lowest Common Ancestor of a
- 236. Lowest Common Ancestor of a
采用递归,分别在左子树和右子树里面查找,如果都能找到,当前节点就是最近共同祖先
如果只能在一个树找到,说明这个数就是最近共同祖先
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if(root == NULL || root == p || root == q)
return root;
struct TreeNode *left = lowestCommonAncestor(root->left, p,q);
struct TreeNode *right = lowestCommonAncestor(root->right, p,q);
if(left&&right)
return root;
if(left)
return left;
if(right)
return right;
return NULL;
}
网友评论