Binary Tree Paths
Recursion
Time Complexity
O(N)
Space Complexity
O(logn)
思路
树的前序遍历,递归的终止条件的第一个root == null,另一个终止条件是当root是叶子节点的时候,就不用再往下递归了,同时加上自己的值,加入res
代码
public List<String> binaryTreePaths(TreeNode root) {
// Write your code here
List<String> res = new ArrayList<String>();
if(root == null) return res;
String path = "";
helper(root, path, res);
return res;
}
private void helper(TreeNode root, String path, List<String> res){
if(root == null) return;
if(root.left == null && root.right == null){
path += root.val;
res.add(path);
return;
}
path += root.val + "->";
helper(root.left, path, res);
helper(root.right, path, res);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。