LeetCode[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"]
Recursion
复杂度
O(N), O(H)
思路
基本算法,递归。
代码
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new LinkedList<>();
helper(root, "", list);
return list;
}
public void helper(TreeNode root, String cur, List<String> list) {
if(root == null) return null;
cur += root.val;
if(root.left == null && root.right == null) {
list.add(cur);
return;
}
cur += "->";
helper(root.left, cur, list);
helper(root.right, cur, list);
}
Iteration
复杂度
O(N), O(N)
思路
递归用stack和stack进行dfs。
代码
public List<String> paths(TreeNode root) {
StringBuilder builder = new StringBuilder();
List<String> res = new LinkedList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();
Set<TreeNode> set = new HashSet<>();
stack.push(root);
builder.append(root.val);
while(!stack.isEmpty()) {
TreeNode cur = stack.peek();
set.add(cur);
if(cur.left != null && !set.contains(cur.left)) {
builder.append(cur.left.val);
stack.push(cur.left);
continue;
}
if(cur.right != null && !set.contains(cur.right)) {
builder.append(cur.right.val);
stack.push(cur.right);
continue;
}
res.add(builder.toString());
builder.deleteCharAt(builder.length() - 1);
}
return res;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。