
/**
* 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||p==root||q==root)return root;
auto left=lowestCommonAncestor(root->left,p,q);
auto right=lowestCommonAncestor(root->right,p,q);
if(!left)return right;
if(!right)return left;
return root;//左右字数各有一个返回根节点;
}
};
本文介绍了一种解决二叉树中寻找两个节点的最近公共祖先问题的算法。通过递归遍历二叉树,当左右子树各有一个目标节点时,当前节点即为最近公共祖先。
466

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



