这道题是真巧妙,巧妙有两点
- 不用区分两个目标节点,只要命中了,就往上
- 代码可以处理一个节点本来就是另一个节点祖先的情况
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL)
return NULL;
if (root == p || root == q)
return root;
TreeNode* l = lowestCommonAncestor(root->left, p, q);
TreeNode* r = lowestCommonAncestor(root->right, p, q);
if (l != NULL && r != NULL)
return root; // 找到最近公共祖先
if (l != NULL && r == NULL)
return l;
if (l == NULL && r != NULL)
return r;
return NULL;
}
};
标签:lowestCommonAncestor,right,TreeNode,祖先,随想录,二叉树,return,NULL,root
From: https://www.cnblogs.com/huigugu/p/18678826