Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
Soution: DFS
- Recursion维护2个变量:
List<Integer> pathEntry:每条路径的节点值
,List<String> result:结果
- Base Case: root为空,则返回
- 遇到
leaf node
,则根据pathEntry
生成路径,插入result
-
pathEntry.add (root.val);
binaryTreePaths (root.left, pathEntry, result);
binaryTreePaths (root.right, pathEntry, result);
- 要记得每次退出迭代时,清除pathEntry中子节点的状态!!!
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<> ();
List<Integer> pathEntry = new ArrayList<> ();
binaryTreePaths (root, pathEntry, result);
return result;
}
private void binaryTreePaths (TreeNode root, List<Integer> pathEntry, List<String> result) {
if (root == null) {
return;
}
pathEntry.add (root.val);
// 注意需要清除子节点的状态
if (root.left != null) {
binaryTreePaths (root.left, pathEntry, result);
pathEntry.remove (pathEntry.size () - 1);
}
if (root.right != null) {
binaryTreePaths (root.right, pathEntry, result);
pathEntry.remove (pathEntry.size () - 1);
}
if (root.left == null && root.right == null) {
StringBuilder path = new StringBuilder ();
//先让prefix为空,就可以避免到出现 ->1->2->5,多余的箭头
String prefix = "";
for (int num : pathEntry) {
String numStr = Integer.toString (num);
path.append (prefix);
prefix = "->";
path.append (numStr);
}
result.add (path.toString());
}
}
}