还有用stack做dfs、用queue做bfs的方法:
https://leetcode.com/problems/binary-tree-paths/discuss/68278/My-Java-solution-in-DFS-BFS-recursion
/**
* 自己的代码,recursive
* Runtime: 8 ms, faster than 56.83%
* Memory Usage: 38.6 MB, less than 99.07%
*/
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(Integer.toString(root.val));
return res;
}
for (String s : binaryTreePaths(root.left)) // 给左子树的路径加上当前节点,并add进res
res.add(root.val + "->" + s);
for (String s : binaryTreePaths(root.right)) // 给右子树的路径加上当前节点,并add进res
res.add(root.val + "->" + s);
return res;
}
}
/**
* 用helper的recursive方法
* Runtime: 1 ms, faster than 99.88%
* Memory Usage: 38.8 MB, less than 96.40%
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
helper(root, res, new StringBuilder());
return res;
}
private void helper(TreeNode root, List<String> res, StringBuilder path) {
if (root == null)
return;
int len = path.length(); // 记录修改前path的长度,用于还原path
path.append(root.val);
if (root.left == null && root.right == null) // 叶子节点
res.add(path.toString());
else {
path.append("->");
helper(root.left, res, path);
helper(root.right, res, path);
}
path.setLength(len); // 还原path
}
}
/**
* DFS using Deque
* Runtime: 9 ms, faster than 25.39%
* Memory Usage: 39.1 MB, less than 57.05%
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null)
return res;
Deque<TreeNode> nodeD = new LinkedList<>(); // 存储DFS中treenode的stack
Deque<String> strD = new LinkedList<>(); // 存储DFS中string的stack
nodeD.push(root);
strD.push("");
while (!nodeD.isEmpty()) { // DFS
TreeNode currNode = nodeD.pop();
String currStr = strD.pop();
if (currNode.left == null && currNode.right == null)
res.add(currStr + currNode.val);
String path = currStr + currNode.val + "->";
if (currNode.right != null) {
nodeD.push(currNode.right);
strD.push(path);
}
if (currNode.left != null) {
nodeD.push(currNode.left);
strD.push(path);
}
}
return res;
}
}
/**
* BFS using Deque
* Runtime: 9 ms, faster than 25.39%
* Memory Usage: 39.6 MB, less than 15.53%
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null)
return res;
Deque<TreeNode> nodeD = new LinkedList<>(); // 存储BFS中treenode的queue
Deque<String> strD = new LinkedList<>(); // 存储BFS中string的queue
nodeD.offer(root);
strD.offer("");
while (!nodeD.isEmpty()) { // BFS
TreeNode currNode = nodeD.poll();
String currStr = strD.poll();
if (currNode.left == null && currNode.right == null)
res.add(currStr + currNode.val);
String path = currStr + currNode.val + "->";
if (currNode.left != null) {
nodeD.offer(currNode.left);
strD.offer(path);
}
if (currNode.right != null) {
nodeD.offer(currNode.right);
strD.offer(path);
}
}
return res;
}
}