C# 逐层反向打印二叉树

奇数层从左到右打印,偶数层从右到左打印。

例如:

a

b c

d e f g

输出则为 a c b d e f g

View Code
void SpecialPrintTrees(node root)
{
    Node temp;
    Stack stack1 = new Stack();
    Stack stack2 = new Stack();
    stack1.Push(root);
    while(stack1.Count>0||stack2.Count>0)
    {
        while(stack1.Count>0)
        {
            temp = stack1.Pop();
            if(temp.Left!=null)
                Stack2.Push(temp.Left);
            if(temp.Right!=null)
                Stack2.Push(temp.Right);
            Console.Write(temp.Value);
        }
        while(stack2.Count>0)
        {
            temp = stack2.Pop();
            if(temp.Right!=null)
                Stack1.Push(temp.Right);
            if(temp.Left!=null)
                Stack1.Push(temp.Left);
            Console.Write(temp.Value);
        }    
    }
}

 

转载于:https://www.cnblogs.com/Ligeance/archive/2013/03/06/2946364.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值