之字形打印二叉树

题目

  请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推

思路

  这题和从上到下打印二叉树类似https://www.cnblogs.com/tianzeng/p/10186431.html;需要两个栈;打印某一层结点时,把下一层结点保存到相应的栈里

  1. 如果当前层是奇数层,先保存左子结点再保存右子结点到第一个栈里
  2. 如果当前层是偶数层,先保存右子结点再保存左子结点到第二个栈里

输出顺序

1

3    2

4    5    6   7

15 14 13 12 12 10 9 8

为什么用两个栈?

  如果只有一个栈,在打印根结点的时候,先后把2和3保存到栈里,在打印栈顶元素3的时候会把3的子节点(如果有的话)保存到栈里,这样以来,栈顶元素就不是2,无法打印元素2

#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;

struct tree
{
    double data;
    struct tree *left,*right;
    tree(int d=0):data(d)
    {
        left=right=nullptr;
    }
};
class Solution
{
    public:
        void create(tree *&root);
        void print(tree *root);
        void pre_order(tree *root);//中序遍历
        tree *root;    
};
void Solution::create(tree *&root)
{
    double x;
    cin>>x;
    if(x==0)
        root=nullptr;
    else
    {
        root=new tree();
        root->data=x;
        create(root->left);
        create(root->right);
    }
}
void Solution::print(tree *root)
{
    if(!root)
        return;
        
    stack<tree *> s[3];
    int current=1;
    int next=2;
    s[current].push(root);
    
    while(!s[current].empty()||!s[next].empty())
    {
        auto t=s[current].top();
        s[current].pop();
        cout<<t->data<<" ";
        
        if(current==1)
        {
            if(t->left)
                s[next].push(t->left);
            if(t->right)
                s[next].push(t->right);
        }
        else
        {
            if(t->right)
                s[next].push(t->right);
            if(t->left)
                s[next].push(t->left);
        }
        
        if(s[current].empty())
        {
            cout<<endl;
            swap(current,next);
        }
    }
}
void Solution::pre_order(tree *root)
{
    if(root)
    {
        cout<<root->data<<endl;
        pre_order(root->left);
        pre_order(root->right);
    }
}
int main()
{
    Solution s;
    s.create(s.root);
    //s.pre_order(s.root);
    s.print(s.root);
    return 0;
}

 

转载于:https://www.cnblogs.com/tianzeng/p/10187981.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值