My Java solution with StringBuilder may help u


  • 5
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void help(List<String> list, TreeNode node, StringBuilder sb) {
    		if (node == null)
    			return;
    		int len=sb.length();
    		sb.append(node.val);
    		if (node.left == null && node.right == null) {				
    			list.add(sb.toString());
    			sb.setLength(len);
    			return;
    		}
    		sb.append("->");
    		help(list, node.left, sb);
    		help(list, node.right, sb);
    		sb.setLength(len);
    	}
    
    	public List<String> binaryTreePaths(TreeNode root) {
    		List<String> res = new ArrayList<String>();
    		help(res, root, new StringBuilder());
    		return res;
    	}
    }

  • 0
    J

    I do not quite understand why you have to set the new length to the StringBuilder sb. Could you please explain more?

    Thanks!


  • 0

    If u can see the difference of the following solutions, u will understand.

    public class Solution {
    		public void help(List<String> list, TreeNode node, String s) {
    			if (node == null)
    				return;
    			int len = s.length();
    			s += node.val;
    			if (node.left == null && node.right == null) {
    
    				list.add(s);
    				s = s.substring(0, len);
    				return;
    			}
    			s += "->";
    			help(list, node.left, s);
    			help(list, node.right, s);
    			s = s.substring(0, len);
    		}
    
    		public List<String> binaryTreePaths(TreeNode root) {
    			List<String> res = new ArrayList<String>();
    			help(res, root, "");
    			return res;
    		}
    	}
            
    
    
      
       public class Solution {
    		public void help(List<String> list, TreeNode node, String s) {
    			if (node == null)
    				return;
    			if (node.left == null && node.right == null) {
    				list.add(s + node.val);
    				return;
    			}
    			help(list, node.left, s + node.val + "->");
    			help(list, node.right, s + node.val + "->");
    		}
    
    		public List<String> binaryTreePaths(TreeNode root) {
    			List<String> res = new ArrayList<String>();
    			help(res, root, "");
    			return res;
    		}
    	}

  • 0
    J

    Thanks, these two solutions are easy to understand.


Log in to reply
 

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