[JAVA] preorder traversal with stringbuffer / T : O(N), S : O(N)


  • 0
    J
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public String tree2str(TreeNode t) {
            StringBuffer strbuf = new StringBuffer();
            dfs(strbuf, t);
            return strbuf.toString();
        }
        
        public void dfs(StringBuffer strbuf, TreeNode t){
            if(t == null)
                return;
            
            strbuf.append(t.val);
            if(t.left == null && t.right == null){
                return; 
            }
            
            strbuf.append('(');
            dfs(strbuf, t.left);
            strbuf.append(')');
            if(t.right != null){
                strbuf.append('(');
                dfs(strbuf, t.right);
                strbuf.append(')');
            }
                
        }
    }
    

Log in to reply
 

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