您的位置:首页 > 其它

【LeetCode】257.Binary Tree Paths(Easy)解题报告

2018-03-11 10:27 465 查看
【LeetCode】257.Binary Tree Paths(Easy)解题报告

题目地址:https://leetcode.com/problems/binary-tree-paths/description/

题目描述:

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


  返回所有路径。

Solution:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
递归遍历就可以了
time : O(n)
space : O(n)
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if(root == null) return res;
helper(res,root,"");
return res;
}
public void helper(List<String> res, TreeNode root,String path){
if(root.left == null && root.right == null){
res.add(path + root.val);
}
if(root.left!=null){
helper(res,root.left,path + root.val+"->");
}
if(root.right!=null){
helper(res,root.right,path+root.val+"->");
}
}
}


Date:2018年3月11日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode tree