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

剑指offer--面试题8:二叉树的下一个结点

2017-06-30 10:45 489 查看


#include <stdio.h>

struct BinaryTreeNode
{//数据结构
int                    m_nValue;   //数值域
BinaryTreeNode*        m_pLeft;    //左孩子指针
BinaryTreeNode*        m_pRight;   //右孩子指针
BinaryTreeNode*        m_pParent;  //双亲指针
};
/*
如果一个节点有右子树,那么它的下一个节点就是它的右子树中的最左子节点。

     如果没有右子树,且它是父节点的左子节点,那么它的下一个节点就是它的父节点。

     如果一个节点即没有右子树,并且它还是父节点的右子节点,这种情况比较复杂。我们可以沿着指向父节点的指针一直向上遍历,直到找到一个是它父节点的左子节点的节点。如果这样的节点存在,那么这个节点的父节点就是我们要找的下一个节点。

     如果一个节点不满足上述所有情况,那么它应该就是中序遍历的最后一个节点。所以返回NULL
*/
BinaryTreeNode* GetNext(BinaryTreeNode* pNode)
{
if(pNode == NULL)
return NULL;

BinaryTreeNode* pNext = NULL;
if(pNode->m_pRight != NULL)
{
BinaryTreeNode* pRight = pNode->m_pRight;
while(pRight->m_pLeft != NULL)
pRight = pRight->m_pLeft;

pNext = pRight;
}
else if(pNode->m_pParent != NULL)
{
BinaryTreeNode* pCurrent = pNode;
BinaryTreeNode* pParent = pNode->m_pParent;

while(pParent != NULL && pCurrent == pParent->m_pRight)
{
pCurrent = pParent;
pParent = pParent->m_pParent;
}
pNext = pParent;
}
return pNext;
}

// ==================== 辅助代码用来构建二叉树 ====================
BinaryTreeNode* CreateBinaryTreeNode(int value)
{
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->m_nValue = value;
pNode->m_pLeft = NULL;
pNode->m_pRight = NULL;
pNode->m_pParent = NULL;

return pNode;
}
void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
{
if(pParent != NULL)
{
pParent->m_pLeft = pLeft;
pParent->m_pRight = pRight;

if(pLeft != NULL)
pLeft->m_pParent = pParent;
if(pRight != NULL)
pRight->m_pParent = pParent;
}
}
//            8
//        6      10
//       5 7    9  11

int main(int argc, char* argv[])
{
BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);
BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
BinaryTreeNode* pNode11 = CreateBinaryTreeNode(11);

ConnectTreeNodes(pNode8, pNode6, pNode10);
ConnectTreeNodes(pNode6, pNode5, pNode7);
ConnectTreeNodes(pNode10, pNode9, pNode11);

printf("            8              \n");
printf("           /  \\           \n");
printf("          6    10           \n");
printf("         /\\   / \\        \n");
printf("        5  7 9   11         \n");
printf("中序遍历序列为:5 6 7 8 9 10 11\n");

printf("5的中序遍历下一个结点为:%d\n",GetNext(pNode5)->m_nValue);
printf("6的中序遍历下一个结点为:%d\n",GetNext(pNode6)->m_nValue);
printf("7的中序遍历下一个结点为:%d\n",GetNext(pNode7)->m_nValue);
printf("8的中序遍历下一个结点为:%d\n",GetNext(pNode8)->m_nValue);
printf("9的中序遍历下一个结点为:%d\n",GetNext(pNode9)->m_nValue);
printf("10的中序遍历下一个结点为:%d\n",GetNext(pNode10)->m_nValue);
printf("11的中序遍历下一个结点为NULL!\n");

return 0;

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: