您的位置:首页 > 职场人生

2017百度面试现场coding算法三

2017-04-23 19:00 309 查看
三、求有孩子和兄弟指针树的最小公共子节点

struct TreeNode
{
int value;
TreeNode* first_child;
TreeNode* next_sibling;
TreeNode(int a):value(a),first_child(NULL),next_sibling(NULL){}
};
bool hasNode(TreeNode* pNode,TreeNode* p)
//判断以pNode为根的树中有没有节点
{
bool flag1=false,flag2=false;
if(pNode==NULL) return false;
if(pNode==p)return true;//当前节点即是访问节点
else
{
if(pNode->first_child!=NULL)
{flag1=hasNode(pNode->first_child, p);//节点在孩子节点
TreeNode* p1=pNode->first_child;
while(p1->next_sibling!=NULL)//在同层兄弟节点中?
{
if(hasNode(p1->next_sibling, p))//找到
{   flag2=true;
break;
}
p1=p1->next_sibling;//循环查找是否在同层的其他节点
}
}
}
return flag1||flag2;//只要包含在孩子或者孩子的兄弟节点中
}
TreeNode* pubParent(TreeNode* root,TreeNode* p,TreeNode* q)
{
TreeNode* pNode=root;
while(hasNode(pNode, p)&&hasNode(pNode, q))//当前节点包含两个节点
{
bool flag1=false,flag2=false;
if(pNode->first_child!=NULL&&hasNode(pNode->first_child, p)&&hasNode(pNode->first_child, q))
//判断是否在孩子节点所在的树中
{    pNode=pNode->first_child,flag1=true;}
else if(pNode->first_child->next_sibling!=NULL)//判断是否在孩子同层的某个兄弟树中
{
TreeNode* p1=pNode->first_child;
while(p1->next_sibling!=NULL)
{
if(hasNode(p1->next_sibling, p)&&hasNode(p->next_sibling, q))//找到包含的兄弟树
{    pNode=p1->next_sibling;
//继续以兄弟树为根查找
flag2=true;
break;
}
else
p1=p1->next_sibling;
}
if(flag2==true)//当包含在其中之一的兄弟节点,则以该节点为根,继续查找
break;
}
if(flag1==false&&flag2==false)//若没有在孩子节点和孩子的兄弟节点中,则只在当前节点中,返回当前节点
return pNode;
}
return pNode;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 百度 面试