JAVA Solution Backtracking


  • 0
    L
    public static List<String> binaryTreePaths(TreeNode root) {
    	List<String> resultList = new ArrayList<String>();
    	if(root == null)
    		return resultList;
    	
    	String result = String.valueOf(root.val);
    	inorder(root, result, resultList);
    	return resultList;
    	
    }
    
    public static void inorder(TreeNode root, String result, List<String> resultList){
    	if(root.left == null && root.right == null)
    		resultList.add(result);
    	
    	if(root.left != null){
    		result += "->" + root.left.val;
    		inorder(root.left, result, resultList);
    		result = result.substring(0, result.lastIndexOf("->"));
    	}
    	if(root.right != null){
    		result += "->" + root.right.val;
    		inorder(root.right, result, resultList);
    		result = result.substring(0, result.lastIndexOf("->"));
    	}
    }

  • 0
    Q

    My Simple Java Solution :

    public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {

        ArrayList<String> ret = new ArrayList<String>();
        String s = "";
        btPath(ret, root, s);
        return ret;
    }
    
    public void btPath(ArrayList<String> ret, TreeNode root, String s){
        if(root == null) return;
    
        s += String.valueOf(root.val);
        if(root.left ==  null && root.right == null){
            ret.add(s);
            return;
        }
        btPath(ret, root.left, s+"->");
        btPath(ret, root.right, s+"->");
        s.substring(0, s.length()-1);
        return;
    }
    

    }


Log in to reply
 

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