您的位置:首页 > 其它

Leetcode no. 257

2016-05-26 01:15 423 查看
257. Binary Tree Paths

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"]


/**
* 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 LinkedList<>();
if (root==null) return res;
search(root, "", res);
return res;
}
private void search(TreeNode root, String s, List<String> list){
if (root.left==null && root.right==null) list.add(s+root.val);
if (root.left!=null) search(root.left, s+root.val+"->", list);
if (root.right!=null) search(root.right, s+root.val+"->", list);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: