SpiralOrderTraverse,螺旋遍历二叉树,利用两个栈
问题描述:s型遍历二叉树,或者反s型遍历二叉树
算法分析:层序遍历二叉树只需要一个队列,因为每一层都是从左往右遍历,而s型遍历二叉树就要用两个栈了,因为每次方向相反。
public static void SpiralOrderTraverse(TreeNode t) { Stack<TreeNode> stack1 = new Stack<>(); Stack<TreeNode> stack2 = new Stack<>(); stack1.push(t); while (!stack1.isEmpty() || !stack2.isEmpty()) { while (!stack1.isEmpty()) { TreeNode tn = stack1.pop(); System.out.print(tn.val + " "); if (tn.right != null) { stack2.push(tn.right); } if (tn.left != null) { stack2.push(tn.left); } } while (!stack2.isEmpty()) { TreeNode tn = stack2.pop(); System.out.print(tn.val + " "); if (tn.left != null) { stack1.push(tn.left); } if (tn.right != null) { stack1.push(tn.right); } } } }