码迷,mamicode.com
首页 > 其他好文 > 详细

之字形打印二叉树

时间:2019-07-13 20:01:06      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:printf   cto   color   amp   二叉树   turn   ||   ace   create   

#include <bits/stdc++.h>
using namespace std;


struct TreeNode
{
    int val;
    TreeNode* left;
    TreeNode* right;
};

void create(TreeNode* &root)
{
    int x;
    cin>>x;
    if(x == 0)
    {
        root = NULL;
        return;
    }
    root = (TreeNode*)malloc(sizeof(TreeNode));
    root->val = x;
    create(root->left);
    create(root->right);
}

// 之字形打印
vector<int> PrintZhiTree(TreeNode* root)
{
    stack<TreeNode*>S1;
    stack<TreeNode*>S2;
    vector<int>V;
    if(!root) return V;
    S1.push(root);
    while(!S1.empty()||!S2.empty())
    {
        while(!S1.empty())
        {
            TreeNode* p = S1.top();
            S1.pop();
            if(!p) continue;
            S2.push(p->left);
            S2.push(p->right);
            V.push_back(p->val);
        }
        V.push_back(0);
        while(!S2.empty())
        {
            TreeNode* p = S2.top();
            S2.pop();
            if(!p) continue;
            S1.push(p->right);
            S1.push(p->left);
            V.push_back(p->val);
        }
        V.push_back(0);
    }
    return V;
}
vector<int> PrintFromTopToBottom(TreeNode* root)
{
    queue<TreeNode*>Q;
    vector<int>V;
    if(!root) return V;
    Q.push(root);
    while(!Q.empty())
    {
        TreeNode* p = Q.front();
        Q.pop();
        if(!p) continue;
        Q.push(p->left);
        Q.push(p->right);
        V.push_back(p->val);
    }
    return V;
}

int main()
{
    TreeNode* root;
    create(root);
    vector<int>V;
    //V = PrintFromTopToBottom(root);
    V = PrintZhiTree(root);
    for(int i=0; i<V.size(); i++)
    {
        if(V[i] ==  0)
            puts("");
        else
            printf("%d ", V[i]);
    }
    return 0;
}

测试:

1 2 4 8 16 0 0 17 0 0 9 18 0 0 19 0 0 5 10 20 0 0 21 0 0 11 22 0 0 23 0 0 3 4 12 24 0 0 25 0 0 13 26 0 0 27 0 0 7 14 28 0 0 29 0 0 15 30 0 0 31 0 0

技术图片

 

之字形打印二叉树

标签:printf   cto   color   amp   二叉树   turn   ||   ace   create   

原文地址:https://www.cnblogs.com/lesroad/p/11181692.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!