从上往下打印二叉树 【微软面试100题 第十六题】

 题目要求:

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

  例如输入下图的二叉树,则依次打印出10,5,12,4,7

      10
     / \
    5   12
   / \
  4   7
 参考资料:剑指offer第23题、编程之美3.10

题目分析:
使用一个辅助队列,队列中的每个元素都是一个指向结点的指针,用递归的方法把二叉树每层依次压入栈中,层与层之间用NULL隔开。
代码实现:
#include <iostream>
#include <queue>

using namespace std;

typedef struct BinaryTree
{
    struct BinaryTree *left,*right;
    int data;
}BinaryTree;

void initTree(BinaryTree **p);
void PrintTreeByLevel(BinaryTree *root);

int main(void)
{
    BinaryTree *root;
    initTree(&root);
    cout << "二叉树为:";
    PrintTreeByLevel(root);

    return 0;
}
//分层遍历二叉树,见编程之美3.10
void PrintTreeByLevel(BinaryTree *root)
{
    if(root==NULL)
        return;
    queue<BinaryTree *> Q;
    Q.push(root);
    Q.push(0);
    while(!Q.empty())
    {
        BinaryTree *tmp = Q.front();
        Q.pop();
        if(tmp)
        {
            cout << tmp->data << " ";
            if(tmp->left)
                Q.push(tmp->left);
            if(tmp->right)
                Q.push(tmp->right);
        }
        else if(!Q.empty())
        {
            Q.push(0);
        }
    }
    cout << endl;
}

//      10
//     / \
//    5   12
//   / \
//  4   7
void initTree(BinaryTree **p)
{
    *p = new BinaryTree;
    (*p)->data = 10;
 
    BinaryTree *tmpNode = new BinaryTree;
    tmpNode->data = 5;
    (*p)->left = tmpNode;
 
    tmpNode = new BinaryTree;
    tmpNode->data = 12;
    (*p)->right = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
    BinaryTree *currentNode = (*p)->left;
 
    tmpNode = new BinaryTree;
    tmpNode->data = 4;
    currentNode->left = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
    tmpNode = new BinaryTree;
    tmpNode->data = 7;
    currentNode->right = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
}
View Code

posted on 2014-10-28 18:02  tractorman  阅读(180)  评论(0编辑  收藏  举报

导航