Last active
August 29, 2015 14:13
-
-
Save dmnugent80/d049f8a0eb5e10f56677 to your computer and use it in GitHub Desktop.
Print each level of a BST on it's own line
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
//Breadth First Search, traverse tree and print it out level-by-level | |
public class TreeNode{ | |
public int data; | |
public int level; | |
public TreeNode left; | |
public TreeNode right; | |
public TreeNode(int d, int l){ | |
this.data = d; | |
this.level = l; | |
this.left = null; | |
this right = null; | |
} | |
} | |
public class BinaryTree{ | |
public TreeNode root; | |
public BinaryTree(){ | |
this.root = null; | |
} | |
public void setLevels(TreeNode node, int l){ | |
if (node != null){ | |
node.level = l; | |
setLevels(node.left, level + 1); | |
setLevels(node.right, level + 1); | |
} | |
} | |
public void printEachTreeLevel(TreeNode root){ | |
Queue<TreeNode> treeQueue = new LinkedList<TreeNode>(); | |
if (root == null){ | |
return; | |
} | |
//set levels, just in case | |
setLevels(root, 0); | |
//Start Breadth first traversal of tree | |
treeQueue.clear(); | |
treeQueue.add(root); | |
while (!(treeQueue.size() == 0)){ | |
TreeNode node = treeQueue.remove(); | |
System.out.print(node.data + " "); | |
//If we are at the end of a level, start a new line | |
if (node.level != treeQueue.peek().level){ | |
System.out.println(); | |
} | |
if (node.left != null){ | |
treeQueue.add(node.left); | |
} | |
if (node.right != null){ | |
treeQueue.add(node.right); | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment