
递归,考虑4种情况。
- pq不在左右子树,返回NULL
- pq同时在左子树,返回left
- pq同时在右子树,返回right
- pq分别在左右子树,返回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 || root==p || root==q) return root;
TreeNode* left=lowestCommonAncestor(root->left,p,q);
TreeNode* right=lowestCommonAncestor(root->right,p,q);
if(!left && !right) return NULL;
else if(left && !right) return left;
else if(!left && right) return right;
return root;
}
};
本文介绍了一种解决二叉树中寻找两个节点最近公共祖先问题的递归算法。通过四种情况的判断:pq不在左右子树、同时在左子树、同时在右子树、分别在左右子树,实现了高效查找。
291

被折叠的 条评论
为什么被折叠?



