Java Inorder 20 ms (Beats 100%)


  • 0
    K
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public String tree2str(TreeNode t) {
            StringBuilder str = new StringBuilder();
            inorder(str, t);
            return str.toString();
        }
        
        public void inorder(StringBuilder result, TreeNode root)
        {
            if(root != null)
            {
                result.append(root.val + "");
                if(root.left == null && root.right == null)
                    return;
                if(root.left != null)
                {
                    result.append("(");
                    inorder(result,root.left);
                    result.append(")");
                }
                if(root.right != null)
                {
                    if(root.left == null)
                        result.append("()");
                    result.append("(");
                    inorder(result,root.right);
                    result.append(")");
                }
            }
            return;
        }
    }
    

Log in to reply
 

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