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); } } }