Created
November 15, 2012 03:15
-
-
Save zac-xin/4076432 to your computer and use it in GitHub Desktop.
Print a binary tree in zig zag level order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Print a binary tree in zig zag level order | |
| */ | |
| package Chapter4; | |
| import java.util.Stack; | |
| public class PrintZigZagOrder { | |
| public static void main(String args[]){ | |
| TreeNode n1 = new TreeNode(1, null, null); | |
| TreeNode n2 = new TreeNode(2, n1, null); | |
| TreeNode n4 = new TreeNode(4, null, null); | |
| TreeNode n6 = new TreeNode(6, null, null); | |
| TreeNode n5 = new TreeNode(5, n4, n6); | |
| TreeNode n3 = new TreeNode(3, n2, n5); | |
| TreeNode n10 = new TreeNode(10, null, null); | |
| TreeNode n11 = new TreeNode(11, n10, null); | |
| TreeNode n9 = new TreeNode(9, null, n11); | |
| TreeNode n8 = new TreeNode(8, null, n9); | |
| TreeNode n7 = new TreeNode(7, n3, n8); | |
| printZigZagOrder(n7); | |
| } | |
| public static void printZigZagOrder(TreeNode root){ | |
| Stack<TreeNode> s1 = new Stack<TreeNode>(); | |
| Stack<TreeNode> s2 = new Stack<TreeNode>(); | |
| Stack<TreeNode> tmp; | |
| s1.add(root); | |
| boolean leftToRight = false; | |
| while(!s1.isEmpty()){ | |
| TreeNode n = s1.pop(); | |
| System.out.print(n.data + " "); | |
| if(!leftToRight){ | |
| if(n.left != null){ | |
| s2.push(n.left); | |
| } | |
| if(n.right != null){ | |
| s2.push(n.right); | |
| } | |
| }else{ | |
| if(n.right != null){ | |
| s2.push(n.right); | |
| } | |
| if(n.left != null){ | |
| s2.push(n.left); | |
| } | |
| } | |
| if(s1.isEmpty()){ | |
| leftToRight = !leftToRight; | |
| System.out.println(); | |
| tmp = s1; | |
| s1 = s2; | |
| s2 = tmp; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment