Clear Java Solution


  • 0
    L
    public class Solution {
        List<String> result = new LinkedList<String>();
        public List<String> binaryTreePaths(TreeNode root) {
            if (root == null) {
                return result;
            }
            childBinaryTreePath(root, "");
            
            return result;
        }
        
        public void childBinaryTreePath(TreeNode root, String path) {
            path += root.val;
            
            if (root.left == null && root.right == null) {
                result.add(path);
            } 
            if (root.left != null) {
                childBinaryTreePath(root.left, path + "->");
            }
            if (root.right != null) {
                childBinaryTreePath(root.right, path + "->");
            }
        }
    }

  • 0
    S

    public List<String> binaryTreePaths(TreeNode root) {
    ArrayList<String> strList = new ArrayList<>();
    if (root == null)
    return strList;
    String temp = root.val + "";
    if (root.left == null && root.right == null)
    strList.add(temp);
    childPaths(strList, root.left, temp);
    childPaths(strList, root.right, temp);
    return strList;
    }

    private void childPaths(ArrayList<String> strList, TreeNode root, String string) {
        if (root == null)
            return;
        string = string + "->" + root.val;
        if (root.left == null && root.right == null) {
            strList.add(string);
            return;
        } else {
            childPaths(strList, root.left, string);
            childPaths(strList, root.right, string);
        }
    }

Log in to reply
 

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