Simple Java DFS


  • 0
    T

    DFS

    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            ArrayList<String> list = new ArrayList<String>();
            if (root == null) return list;
            paths(root, list, "");
            return list;
        }
        
        private void paths(TreeNode root, ArrayList<String> list, String path) {
            if (root == null)
                return;
            if (root.left == null && root.right == null) {
                path += root.val;
                list.add(path);
            } else {
                paths(root.left, list, path+root.val+"->");
                paths(root.right, list, path+root.val+"->");
            }
        }
    }
    

Log in to reply
 

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