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; }
相关文章推荐
- 2017百度面试现场coding算法二
- 2017百度面试现场coding算法一
- 百度2017校招面试总结
- 百度数据挖掘实习工程师一、二现场面试(深圳)
- 2017阿里,百度,京东java面试+笔试大合集,2018的你会吗?
- 2017面试笔试题总结(58、滴滴、百度、中兴、美团等)
- 2017阿里,百度,京东java面试+笔试大合集
- 百度开发测试面试经验2017
- 2017 秋招 百度二轮面试—血淋淋的经历写实
- 2017暑期实习生面试--百度,freewheel
- 百度数据挖掘实习工程师一、二现场面试(深圳)
- 百度实习生面试经历(offer'已拿)
- 百度面试总结
- 面试宝典之二 百度算法面试题分析
- 2017 计蒜之道 初赛 第二场 B. 百度的科学计算器(简单)
- 面试总结(百度(后台)、腾讯(客户端)、锐捷网络)
- 2016届校招 百度WEB前端研发【实习生+提前批】面试经历
- 2012应届生百度面试
- 百度面试及总结3
- 2017安阳市“政府购岗”招聘面试人员名单的公告