[15ms] Fast and simple Tree traversal Java Solution


  • 0
    L

    The problem focuses on appending the left nodes even if null.

    sb.append() blocks are written above the if condition for root.left whereas they are written inside the if condition for root.right.

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

Log in to reply
 

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