#include <iostream>
#include <vector>
using std::endl;
using std::vector;
using std::cin;
using std::cout;
struct treeNode
{
int value;
treeNode*left;
treeNode*right;
};
<strong><span style="font-size:18px;">bool isAncestor(treeNode*root,treeNode*p)
{
if(root==NULL)
return false;
if(root==p)
return true;
return isAncestor(root->left,p)||isAncestor(root->right,p);
}
treeNode* findCommonAncestor(treeNode* root,treeNode* p,treeNode *q)
{
if(root==NULL)
return NULL;
if(root==p||root==q)
return root;
bool is_p_left=isAncestor(root->left,p);//p在左子树
bool is_q_left=isAncestor(root->left,q);//q在左子树
if (is_p_left!=is_q_left)//p、q异侧
return root;
return is_p_left?findCommonAncestor(root->left,p,q):findCommonAncestor(root->right,p,q);
}
treeNode *findAncestor(treeNode* root,treeNode*p, treeNode*q)
{
if(!isAncestor(root
二叉树公共祖先节点的查找
最新推荐文章于 2023-10-21 11:44:48 发布