【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日