2017百度面試現場coding算法三

三、求有孩子和兄弟指針樹的最小公共子節點

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章