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"]
题目分析:DFS即可 (16ms 击败76%)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void DFS(TreeNode root, List<String> ans, String cur) {
if (root.left == null && root.right == null) {
ans.add(cur);
return;
}
if (root.left != null) {
DFS(root.left, ans, cur + "->" + root.left.val);
}
if (root.right != null) {
DFS(root.right, ans, cur + "->" + root.right.val);
}
}
public List<String> binaryTreePaths(TreeNode root) {
List<String> ans = new ArrayList<>();
if (root == null) {
return ans;
}
DFS(root, ans, root.val + "");
return ans;
}
}