//说明:
//1.所有的节点值都是唯一的
//2.p,q为不同节点且均存在于二叉树中
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
class solution
{
TreeNode* lowestCommonAncestor(TreeNode* root,int p,int 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 root;
if(left && !right) return left;
return right;
}
};
寻找二叉树中的首个共同祖先C++实现
最新推荐文章于 2023-07-22 12:51:12 发布