257. Binary Tree Paths

来源:互联网 发布:seo软件下载 编辑:程序博客网 时间:2024/06/06 11:43

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

["1->2->5", "1->3"]


public List<String> binaryTreePaths(TreeNode root) {        List<String> res = new ArrayList<String>();        if(root!=null)            helper(root, Integer.toString(root.val), res);        return res;    }        public void helper(TreeNode root, String path, List res){        if(root.left==null&&root.right==null){            res.add(path);        }        if(root.left!=null){            helper(root.left, path + "->" + root.left.val, res);        }        if(root.right!=null){            helper(root.right, path + "->" + root.right.val, res);        }    }


0 0