Java Recursive solution


  • 0
    S
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res = new ArrayList<String>();
            if(root == null) return res;
            util(res, root, "");
            return res;
        }
        
        void util(List<String> res, TreeNode root, String current) {
            if(root.right!=null)
                util(res, root.right, current+ root.val + "->");
            if(root.left!=null)
                util(res, root.left,current + root.val + "->");
            if(root.right == null && root.left == null) res.add(current + root.val);
        }
    }
    

Log in to reply
 

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