Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class TreeNode {
- private int data;
- private TreeNode rightChild;
- private TreeNode leftChild;
- private static int COUNT;
- public TreeNode(int data) {
- this.data = data;
- this.rightChild = null;
- this.leftChild = null;
- }
- public static void fillInLevel(int level, TreeNode root) {
- helper( root, level);
- }
- public static void helper( TreeNode node, int level) {
- // If it's empty and within level, fill -1
- if ( node == null)
- node = new TreeNode(-1);
- if ( node.leftChild == null )
- node.setLeftChild(new TreeNode(-1));
- if ( node.rightChild == null )
- node.setRightChild(new TreeNode(-1));
- while( level > 1) {
- helper(node.leftChild, level-=1);
- helper(node.rightChild, level-=1);
- }
- return;
- }
- public TreeNode getRightChild() {
- return rightChild;
- }
- public void setRightChild(TreeNode rightChild) {
- COUNT++;
- this.rightChild = rightChild;
- }
- public TreeNode getLeftChild() {
- return leftChild;
- }
- public void setLeftChild(TreeNode leftChild) {
- COUNT++;
- this.leftChild = leftChild;
- }
- static void print2DUtil(TreeNode root, int space)
- {
- // Base case
- if (root == null)
- return;
- // Increase distance between levels
- space += COUNT;
- // Process right child first
- print2DUtil(root.rightChild, space);
- // Print current node after space
- // count
- System.out.print("\n");
- for (int i = COUNT; i < space; i++)
- System.out.print(" ");
- System.out.print(root.data + "\n");
- // Process left child
- print2DUtil(root.leftChild, space);
- }
- // Wrapper over print2DUtil()
- static void print2D(TreeNode root)
- {
- // Pass initial space count as 0
- print2DUtil(root, 0);
- }
- Current result
- -1
- 7
- -1
- 2
- -1
- 13
- -1
- 5
- 11
- 3
- 31
- 29
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement