0

Printing Boundary of a binary tree in java.(anticlockwise wise from root) divided the problem in three parts.

  1. first printing left subtree boundary without bottom most leaf.
  2. printing all the leaves from left to right.
  3. saving all the tree nodes data in a string for right subtree boundary without bottom most leaf as in part 1. saving in a string , as the nodes will traverse from top down and i want bottom up to be in anticlockwise mode. then printing the string from end to first character. ...

Test case: 1 2 3 -1 5 6 -1 -1 -1 -1 -1 (Level order input with -1 denoting no node)

Error: Runtime Error (NZEC)

Exception in thread main java.lang.NullPointerException at Solution.pleft(Solution.java:31) at      (first if condition in pleft method)
 Solution.pleft(Solution.java:37) at
 Solution.pleft(Solution.java:37) at.... (pleft(root.left); in  pleft method)
 Solution.solve(Solution.java:19) at.... (pleft(room); statement in solve method)
 Runner.main(Runner.java:60)

Code:

    /*
Class used for BinaryTreeNode

class BinaryTreeNode<T> {
    T data;
    BinaryTreeNode<T> left;
    BinaryTreeNode<T> right;

    BinaryTreeNode(T data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
*/

public class Solution {
    public static void solve(BinaryTreeNode<Integer> root){
        if(root==null)
            return;
        System.out.print(root.data+" ");
        pleft(root.left);
        leaf(root.left);
        leaf(root.right);
        StringBuffer s=new StringBuffer();
        s=pright(root.right,s);
        if(s.length()!=0){
            for(int i=s.length()-1;i>-1;i--){
                System.out.print(s.charAt(i)+" ");
            }
        }
    }
    static void pleft(BinaryTreeNode<Integer> root){
        if(root==null){
            return;
        }
        if(root.left==null && root.right==null)
            return;
        System.out.print(root.data+" ");
        if(root.left==null){
            pleft(root.right);
        }
        pleft(root.left);
    }
    static StringBuffer pright(BinaryTreeNode<Integer> root, StringBuffer s){// store in string then print
        if(root==null){
            return new StringBuffer();
        }
        if(root.left==null && root.right==null)
            return s;
        s.append(Integer.toString(root.data));
        if(root.right==null){
            return pright(root.left,s);
        }
        return pright(root.right,s);

    }
    static void leaf(BinaryTreeNode<Integer> root){
        if(root==null) return;
        if(root.left==null&&root.right==null){
            System.out.print(root.data+" ");
        }
        leaf(root.left);
        leaf(root.right);
    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41

0 Answers0