2MS Clean Java Code


  • 2
    J

    public class Solution {

    /**
     * Check the true tree root, then explore each subtree.
     * 
     * @param root
     * The root of the tree.
     */
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        
        // The root has no children!
        if(root.left == null && root.right == null){
            result.add(Integer.toString(root.val));
            return result;
        }
        
        // Check the left subtree and append our root's value.
        if(root.left != null){
            createPath(root.left, Integer.toString(root.val), result);
        }
    
        // Check the right subtree and append our root's value.    
        if(root.right != null){
            createPath(root.right, Integer.toString(root.val), result);
        }
        
        return result;
    }
    
    /**
     * Appends the nodes current value to the path and checks whether it's a leaf or
     * has children.
     * 
     * @param root
     * The node we are visiting.
     * 
     * @param current
     * The current path to the root node.
     * 
     * @param result
     * Our result list which is appended to at each leaf node.
     */
    public void createPath(TreeNode root, String current , List<String> result){
        current += "->" + Integer.toString(root.val);
        
        // Found a solution!
        if(root.left == null && root.right == null){
            result.add(current);
        }
        
        // Visit left subtree.
        if(root.left != null){
            createPath(root.left, current, result);
        }
        
        // Visit right subtree.
        if(root.right != null){
            createPath(root.right, current, result);
        }
        
    }
    

    }


Log in to reply
 

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