Simple Java Preorder traversal solution


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

    Also, viewable here on Github.


Log in to reply
 

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