您的位置:首页 > 其它

5.1.11—二叉树的遍历—Flatten Binary Tree to Linked List

2017-08-07 21:34 507 查看
描述

Given a binary tree, flaen it to a linked list in-place.

For example, Given

  1

 / \

 2  5

/ \  \

3 4   6

e flaened tree should look like:

1

\

2

\

3

\

4

\

5

\

6

#include "BinaryTree.h"
#include<vector>
using namespace std;
//===将一棵二叉树就地转化为单链表---递归版本
void FlatBinTreeToLinkList(BinaryTreeNode *proot)
{
if (!proot) return;
if (proot->m_pLeft) FlatBinTreeToLinkList(proot->m_pLeft);
if (proot->m_pRight) FlatBinTreeToLinkList(proot->m_pRight);

if (proot->m_pLeft == NULL) return;

BinaryTreeNode *temp = proot->m_pRight;
BinaryTreeNode *p = proot->m_pLeft;
while (p->m_pRight) p = p->m_pRight;

p->m_pRight = temp;
proot->m_pRight = proot->m_pLeft;
proot->m_pLeft = NULL;
}
//===将一棵二叉树就地转化为单链表---迭代版本
void FlatBinTreeToLinkList1(BinaryTreeNode *proot)
{
if (!proot) return;
BinaryTreeNode *cur = proot;
while (cur)
{
if (cur->m_pLeft)
{

BinaryTreeNode *p_left = cur->m_pLeft;
BinaryTreeNode *p_right = cur->m_pRight;
while (p_left->m_pRight) p_left = p_left->m_pRight;
cur->m_pRight = cur->m_pLeft;
cur->m_pLeft = NULL;
p_left->m_pRight = p_right;
}
cur = cur->m_pRight;
}
}
// ====================测试代码====================
//            8
//        6      10
//       5 7    9  11
int main()
{
//===
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);

//===
//PrintTree(pNode8);
//===
//FlatBinTreeToLinkList(pNode8);
//PrintTree(pNode8);
//===
FlatBinTreeToLinkList1(pNode8);
PrintTree(pNode8);

DestroyTree(pNode8);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐