mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-08-06 18:24:23 +08:00
744 B
744 B
链接
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
思路
与其说是递归,不如说是回溯。(要好好讲讲回溯)
如果左孩子出现在左子树,右孩子出现在右子树,那么该节点为最近公共祖先。
最后如果
C++代码
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == q || root == p || root == NULL) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != NULL && right != NULL) return root;
if (left == NULL) return right;
return left;
}
};