Java easy pre-traversal solution


  • 1
    W

    For this question, we may assume in binary tree that a node is only a valid input null when a right child is present and a left child is not.

    public String preTraverse(TreeNode t, String ret){
        
        //simply do nothing and return string
        if(t==null) return ret;
        
        //print current node first 
        ret = ret + t.val;
        
        //if left node is found, print it and surround it with '()'
        if(t.left!=null)
            ret = preTraverse(t.left, ret + "(" ) + ")";
        
        //note that left node may be null with right node filled. Then add empty '()'
        else if (t.left==null && t.right!=null)
            ret = ret+"()";
        
        //if left node is found, print it and surround it with '()'
        if(t.right!=null)
            ret = preTraverse(t.right, ret + "(") +")";
       
        //no need to add '()' for null right node
        return ret;
    }

  • 1
    C

    Be alert to use string + string.... it causes severe performance issue when it is getting big.

    Use StringBuffer or StringBuilder instead


  • 0
    W

    @chenw2000 good point thanks!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.