Question
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"]
Java Code
public List<String> binaryTreePaths(TreeNode root) {
String path = new String();
List<String> pathList = new LinkedList<String>();
if(root == null) return pathList;//空树则返回空的pathList(空List不等同于null)
recordPath(root, path, pathList);
return pathList;
}
//DFS遍历二叉树,并一直传递当前的路径path和所有的路径pathList
public void recordPath(TreeNode root, String path, List<String> pathList) {
//如果已经到达叶子节点,在pathList中记录该条路径,结束该条路径的遍历
if(root.left == null && root.right == null) {
pathList.add(path + root.val);
return;
}
//如果存在左子节点,在当前路径中加入当前节点,并继续遍历左子树
if(root.right != null)
recordPath(root.right, path + root.val + "->", pathList);
//如果存在右子节点,在当前路径中加入当前节点,并继续遍历右子树
if(root.left != null)
recordPath(root.left, path + root.val + "->", pathList);
}
说明
- 代码中递归函数recordPath的特点是,每次递归深入时即遍历二叉树下一层节点时,将当前节点添加到path字符串中,从而path中按顺序记录了当前节点的所有父辈节点。由于DFS遍历时随时可能遇到叶子节点即到达某条路径的端点,此时我们需要保存path,这无法通过将path作为recordPath的返回值来实现,因为这样会在每一层递归退出时都返回path,而我们只需要保存达到路径端点时的path,所以必须要给递归函数recordPath再传递一个List变量,用于保存每一个完整的path,并且List变量传参时传递的是自身的引用而不是自身的一个副本。