description:
Given a binary tree, return all root-to-leaf paths.
Have you met this question in a real interview? Yes
Example
Given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
[
“1->2->5”,
“1->3”
]
解法:
只要是遇到二叉树的问题,首先想到使用DFS进行处理。一般情况下使用递归的方式就可以顺利解决,使用非递归的方式一般要面到更高级别吧。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
public List<String> binaryTreePaths(TreeNode root) {
// Write your code here
ArrayList<String> result = new ArrayList<>();
if (root == null) {
return result;
}
List<String> left = binaryTreePaths(root.left);
List<String> right = binaryTreePaths(root.right);
// 当此处是叶子结点的时候,for循环直接退出
for (String path : left) {
result.add(root.val + "->" + path);
}
for (String path : right) {
result.add(root.val + "->" + path);
}
// 处理叶子结点的情况
if (result.size() == 0) {
result.add("" + root.val);
}
return result;
}
}