Saturday, October 10, 2015

Print boundary nodes of binary tree

This is from LeetCode:

Print all edge nodes of a complete binary tree anti-clockwise.
That is all the left most nodes starting at root, then the leaves left to right and finally all the rightmost nodes.
In other words, print the boundary of the tree.
Variant: Print the same for a tree that is not complete.

The key to solve this problem is to understand recursion and how we use it. Recursion can be done by bottom-up or top-down fashion. Bottom-up approach is to build up the stack until hitting the bottom then start to present the result, top-down approach is to present the result along the way to bottom and terminate at the bottom.

Here is the code. The comments explain what each method tries to accomplish.

    public static class Tree {
        int v;
        Tree left;
        Tree right;
        public Tree(int v){
            this.v = v;
        }
        public Tree(int v, Tree left, Tree right){
            this.v = v;
            this.left = left;
            this.right = right;
        }
    }
  
    public static void printBoundary(Tree root){
        //print left-most from top to bottom
        Tree curr = root;
        printLeftMost(curr);
        //print leaves from left to right
        printLeavesLeftRight(root);
        //print right-most from bottom to top
        printRightMost(root, root);
    }
  
    /**
     * print the right most nodes bottom up
     * and skip the first and last
     * @param root
     * @param first
     */
    public static void printRightMost(Tree root, Tree top){
        if(root.right!=null)
            printRightMost(root.right, top);
        else if(root.left!=null)
            printRightMost(root.left, top);
        if(root!=top && root.left!=null && root.right!=null)
            System.out.println(root.v);
    }
    /**
     * print leaves from left to right
     * and skip the left most leaf
     * and return the last one
     * @param root
     * @param start
     * @return
     */
    public static void printLeavesLeftRight(Tree root){
        if(root==null)
            return;
        printLeavesLeftRight(root.left);
        if(root.left==null && root.right==null){
            System.out.println(root.v);
        }
        printLeavesLeftRight(root.right);
    }
    /**
     * print left most nodes from top to bottom
     * and skip/return the last one
     * @param root
     * @return
     */
    public static void printLeftMost(Tree root){
        if(root.left==null && root.right==null)  
            return;
        System.out.println(root.v);
        if(root.left!=null)
            printLeftMost(root.left);
        else
            printLeftMost(root.right);
    }

No comments:

Post a Comment