您的位置:首页 > Web前端

剑指Offer-23-从上往下打印二叉树

2015-11-16 09:44 330 查看
题目:

从上往下打印二叉树的每个结点,同一层的结点按照从左到右的顺序打印。

思路:

实际该题即为二叉树的层次遍历,可以使用一个辅助队列,打印完某结点后将其左结点和右结点依次加入队列,循环遍历队列,直至队列为空。

#include <iostream>
#include <queue>

using namespace std;
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
};

//二叉树的层次遍历
void LevelPrint(BinaryTreeNode *root) {
if(root == NULL)
return;
std::queue<BinaryTreeNode*> levelQ;
levelQ.push(root);
while(!levelQ.empty())
{
BinaryTreeNode *node = levelQ.front();
cout<<node->m_nValue<<" ";
levelQ.pop();
if(node->m_pLeft) {
levelQ.push(node->m_pLeft);
}
if(node->m_pRight) {
levelQ.push(node->m_pRight);
}
}
cout<<endl;
}

//使用前序遍历和中序遍历的结果构建二叉树
//a前序遍历序列,b中序遍历序列
BinaryTreeNode* build(int*a,int la,int ra,int* b,int lb,int rb) {
if(la > ra)
return NULL;
//用于统计左子树结点个数
int len = 0;
// 在中序遍历中找到根结点的值
for(int i=lb;i<=rb;i++) {
if(a[la] == b[i]) {
break;
}
len++;
}
//创建结点 前序遍历序列的第一个数字是根结点的值
BinaryTreeNode *root = new BinaryTreeNode();
root->m_nValue = a[la];//即 b[lb+len]
//构造左子树,左子树结点个数个数为len
root->m_pLeft = build(a,la+1,la+len,b,lb,lb+len-1);
//构造右子树, 右子树结点个数为rb-lb-len
root->m_pRight = build(a,ra-rb+lb+len+1,ra,b,lb+len+1,rb);
return root;
}

// 普通二叉树
//              1
//           /     \
//          2       3
//         /       / \
//        4       5   6
//         \         /
//          7       8
void Test1()
{
const int length = 8;
int preorder[length] = {1, 2, 4, 7, 3, 5, 6, 8};
int inorder[length] = {4, 7, 2, 1, 5, 3, 8, 6};
BinaryTreeNode *root = build(preorder,0,length-1,inorder,0,length-1);
LevelPrint(root);
}

// 所有结点都没有右子结点
//            1
//           /
//          2
//         /
//        3
//       /
//      4
//     /
//    5
void Test2()
{
const int length = 5;
int preorder[length] = {1, 2, 3, 4, 5};
int inorder[length] = {5, 4, 3, 2, 1};
BinaryTreeNode *root = build(preorder,0,length-1,inorder,0,length-1);
LevelPrint(root);
}

// 所有结点都没有左子结点
//            1
//             \
//              2
//               \
//                3
//                 \
//                  4
//                   \
//                    5
void Test3()
{
const int length = 5;
int preorder[length] = {1, 2, 3, 4, 5};
int inorder[length] = {1, 2, 3, 4, 5};
BinaryTreeNode *root = build(preorder,0,length-1,inorder,0,length-1);
LevelPrint(root);
}

// 树中只有一个结点
void Test4()
{
const int length = 1;
int preorder[length] = {1};
int inorder[length] = {1};
BinaryTreeNode *root = build(preorder,0,length-1,inorder,0,length-1);
LevelPrint(root);
}

int main() {
Test1();
Test2();
Test3();
Test4();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: