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"]
链接: http://leetcode.com/problems/binary-tree-paths/
题解:
求Binary Tree所有路径。用Recursive解法会比较容易。逻辑是,假如为current root为leaf node,则在res中加入该节点,返回。否则,递归求解,在左子树和右子树每一个结果中,在String前面insert root.val + "->"。
Time Complexity - O(n), Space Complexity - O(n)
/**
* 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 ArrayList<>();
if(root == null)
return res;
if(root.left == null && root.right == null) {
res.add(String.valueOf(root.val));
} else {
for(String s : binaryTreePaths(root.left)) {
res.add(String.valueOf(root.val) + "->" + s);
}
for(String s : binaryTreePaths(root.right)) {
res.add(String.valueOf(root.val) + "->" + s);
}
} return res;
}
}
二刷:
还是使用了最简单的DFS Recursive解法。更好的解法可能是stack DFS和queue BFS。
Java:
Time Complexity - O(n), Space Complexity - O(n)
/**
* 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 ArrayList<>();
if (root == null) {
return res;
}
if (root.left == null && root.right == null) {
res.add(root.val + "");
return res;
}
List<String> left = binaryTreePaths(root.left);
List<String> right = binaryTreePaths(root.right);
for (String s : left) {
res.add(root.val + "->" + s);
}
for (String s : right) {
res.add(root.val + "->" + s);
}
return res;
}
}
三刷:
完全忘了一刷二刷是怎么写的,直接就用dfs + backtracking了。辅助方法里面用的是in-order traversal。 这里使用了一个List<Integer>来辅助计算Path,否则单独使用一个StringBuilder并不十分方便。
Java:
Time Complexity - O(n), Space Complexity - O(n)
/**
* 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 ArrayList<>();
List<Integer> path = new ArrayList<>();
getBinaryTreePaths(res, path, root);
return res;
} private void getBinaryTreePaths(List<String> res, List<Integer> path, TreeNode root) {
if (root == null) return;
path.add(root.val);
if (root.left == null && root.right == null) {
StringBuilder sb = new StringBuilder();
for (int val : path) sb.append(val).append("->");
sb.setLength(sb.length() - 2);
res.add(sb.toString());
path.remove(path.size() - 1);
return;
}
getBinaryTreePaths(res, path, root.left);
getBinaryTreePaths(res, path, root.right);
path.remove(path.size() - 1);
}
}
Update:
/**
* 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 ArrayList<>();
binaryTreePaths(res, new ArrayList<Integer>(), root);
return res;
} private void binaryTreePaths(List<String> res, List<Integer> path, TreeNode root) {
if (root == null) return;
path.add(root.val);
if (root.left == null && root.right == null) {
StringBuilder sb = new StringBuilder();
for (int val : path) sb.append(val).append("->");
sb.setLength(sb.length() - 2);
res.add(sb.toString());
path.remove(path.size() - 1);
return;
}
binaryTreePaths(res, path, root.left);
binaryTreePaths(res, path, root.right);
path.remove(path.size() - 1);
}
}
写在一个方法里,仿照一刷二刷的dfs:
这里每次递归都要创建新的ArrayList,并且左右子树都要计算,空间复杂度会比较高。怎么计算清楚,留给下一次了。
/**
* 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 ArrayList<>();
if (root == null) return res;
if (root.left == null && root.right == null) res.add(String.valueOf(root.val)); List<String> left = binaryTreePaths(root.left);
for (String leftPath :left) res.add(root.val + "->" + leftPath); List<String> right = binaryTreePaths(root.right);
for (String rightPath :right) res.add(root.val + "->" + rightPath); return res;
}
}
Reference:
https://leetcode.com/discuss/55451/clean-solution-accepted-without-helper-recursive-function
https://leetcode.com/discuss/52072/accepted-java-simple-solution-in-8-lines
https://leetcode.com/discuss/52020/5-lines-recursive-python
https://leetcode.com/discuss/65362/my-concise-java-dfs-solution
https://leetcode.com/discuss/67749/bfs-with-two-queue-java-solution
257. Binary Tree Paths的更多相关文章
- <LeetCode OJ> 257. Binary Tree Paths
257. Binary Tree Paths Total Accepted: 29282 Total Submissions: 113527 Difficulty: Easy Given a bina ...
- 【LeetCode】257. Binary Tree Paths
Binary Tree Paths Given a binary tree, return all root-to-leaf paths. For example, given the followi ...
- Leetcode 257. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 ...
- (easy)LeetCode 257.Binary Tree Paths
Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 ...
- Java [Leetcode 257]Binary Tree Paths
题目描述: Given a binary tree, return all root-to-leaf paths. For example, given the following binary tr ...
- LeetCode OJ 257. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 ...
- LeetCode 257. Binary Tree Paths (二叉树路径)
Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 ...
- 【一天一道LeetCode】#257. Binary Tree Paths
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...
- [LeetCode&Python] Problem 257. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example ...
随机推荐
- 移植Oracle procedure 到 postgresql
1.登录postgresql psql -h 192.168.137.131 -p 5432 postgres satusc@6789#JKL 2.创建用户 CREATE USER name thun ...
- nginx服务器绑定域名和设置根目录
首先进入nginx安装目录的配置目录conf,然后执行 vi conf/nginx.conf 打开nginx的配置文件,找到并修改红字部分 server { listen default_server ...
- 使用Qpython3制作老版天翼飞TP路由器拨号脚本
#幻境拨号python版 #by 1414641776 account='xxxxxx@96301' password='xxxxx' # 路由器脚本 def sendToRoute(account, ...
- Hadoop分布式安装
一.安装准备 1.下载hadoop,地址:http://hadoop.apache.org/,下载相应版本 2.下载JDK版本:Hadoop只支持1.6以上,地址:ht ...
- Java String.split()注意点
//String[] aa = "aaa|bbb|ccc".split("|");//错误 String[] aa = "aaa|bbb|ccc&qu ...
- 深度分析 Java 的 ClassLoader 机制(源码级别)
写在前面:Java中的所有类,必须被装载到jvm中才能运行,这个装载工作是由jvm中的类装载器完成的,类装载器所做的工作实质是把类文件从硬盘读取到内存中,JVM在加载类的时候,都是通过ClassLoa ...
- 2012 Asia JinHua Regional Contest
Draw Something http://acm.hdu.edu.cn/showproblem.php?pid=4450 o(n)统计输入每个数的平方和. #include<cstdio> ...
- C/C++ 快速排序 quickSort
下面的动画展示了快速排序算法的工作原理. 快速排序图示:可以图中在每次的比较选取的key元素为序列最后的元素. #include <stdio.h> #include <stdlib ...
- 在windows下用FTP命令上传文件到Linux
在桌面新建个文件夹,命名成MySQL.rpm.把需要上传的文件放到这个文件夹里.打开cmd窗口,开始用下面命令操作: C:\Users\huyadi>cd C:\Users\huyadi\Des ...
- StringBuffer 和 StringBuilder
如果你读过<Think in Java>,而且对里面描述HashTable和HashMap区别的那部分章节比较熟悉的话,你一定也明白了原因所在.对,就是支持线程同步保证线程安全而导致性能下 ...