二叉树的最近公共祖先
程序员文章站
2022-07-14 14:42:28
...
Note: 核心想法是看左边有没有,右边有没有。如果左边没有,说明在右边;右边没有,说明在左边;两边都有说明是"root"。
/**
* 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 || root == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left == NULL) {
return right;
}
if(right == NULL) {
return left;
}
return root;
}
};
上一篇: 天池盐城汽车上牌预测
下一篇: LeetCode刷题记录 6-10