面试题八:二叉树的下一个节点

给定一个二叉树和一个节点,如何在中序遍历序列的下一个节点,树中结点不只有左右节点指针,还有一个指向类的指针
分析:在中序遍历中,先边再根节点,再右边
情况1: 如果该节点没有右节点,且是父节点的左节点,下一个节点指向父节点
情况2: 如果有右节点,指向右节点的最左节点
情况3: 如果该节点没有右节点,且还是父节点的右节点,沿着父节点指针一直向上寻找,直到该节点是 该父亲的左子树,返回父亲;
情况4: 如果向上寻找发现该节点没有父节点,那么就null

    BinaryTreeNode* GetNext(BinaryTreeNode  pNode){
        if(pNode == null) return null;
        
        BinaryTreeNode  pNext = null;     
        
        //情况2,有右子树
        if(pNode.Right != null){
             BinaryTreeNode pRight = pNode.Right;
             
            //寻找右子树的最左子树,如果没有,该节点就是了
              while(pRight.Left != null)
                     pRight = pRight.Left;
              pNext = pRight;
        }
        
       //情况1.3
        else if ( pNode.Parent != nullptr){
                BinaryTreeNode  pCurrent = pNode;
                BinaryTreeNode  pParent = pNode.Parent;
                
          //如果没有进入·循环,那么就是情况1,直接返回父节点  
          //情况3
              while(pParent != null && pCurrent == pParen.Right){              
                    pCurrent = pParent;
                    pParent = pParent->m_pParent;
              }
              
              pNext = pParent;
              }
        return pNext;
  }

 

posted @ 2020-03-29 14:22  浪波激泥  阅读(162)  评论(0编辑  收藏  举报