Java non-recursion solution


  • 0
    X
        public String tree2str(TreeNode t) {
            if (t == null) {
                return "";
            }
            
            final StringBuilder sb = new StringBuilder();
            final Stack<TreeNode> stack = new Stack<>();
            stack.push(t);
            
            while (!stack.isEmpty()) {
                final TreeNode node = stack.pop();
                if (node.val == Integer.MIN_VALUE) {
                    sb.append('(');
                } else if (node.val == Integer.MAX_VALUE) {
                    sb.append(')');
                } else {
                    sb.append(node.val);
                }
                
                if (node.left == null && node.right == null) {
                    continue;
                }
                
                if (node.right != null) {
                    stack.push(new TreeNode(Integer.MAX_VALUE));
                    stack.push(node.right);
                    stack.push(new TreeNode(Integer.MIN_VALUE));
                }
                
                stack.push(new TreeNode(Integer.MAX_VALUE));
                if (node.left != null) {
                    stack.push(node.left);
                }
                stack.push(new TreeNode(Integer.MIN_VALUE));
            }
               
            return sb.toString();
        }
    

Log in to reply
 

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