2ms Use StringBuilder!!


  • 1
    Q

    use StringBuilder setLength to remove nodes out of the string

    public class Solution {
        List<String> result;
        public List<String> binaryTreePaths(TreeNode root) {
            result = new ArrayList<String>();
            trav(root, new StringBuilder());
            return result;
        }
        public void trav(TreeNode node, StringBuilder sb){
            if(node == null){
                return;
            }
            int len = sb.length();
            if(sb.length() == 0){
                sb.append(node.val);
            }
            else{
                sb.append("->" + node.val);
            }
            if(node.left == null && node.right == null){
                result.add(sb.toString());
            }
            else{
                trav(node.left, sb);
                trav(node.right, sb); 
            }
            sb.setLength(len);
        }
    }

Log in to reply
 

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