Java preorder traversing


  • 0
    J

    public class Solution {

    private StringBuilder sb = new StringBuilder();
    
    public String tree2str(TreeNode t) {
        preorder(t);
        
        return sb.toString();
    }
    
    public void preorder(TreeNode t) {
        if (t == null) {
            return;
        }
        
        sb.append(t.val);
        
        if (t.left != null || t.right != null) sb.append("(");
        
        tree2str(t.left);
        
        if (t.left != null || t.right != null) sb.append(")");
        if (t.right != null) sb.append("(");
        
        tree2str(t.right);
        
        if (t.right != null) sb.append(")");
    }
    

    }


Log in to reply
 

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