题目描述:
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"]
解题思路:
使用递归法。
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
if(root != null)
searchTree(res, root, "");
return res;
} public void searchTree(List<String> res, TreeNode root, String connection){
if(root.left == null && root.right == null)
res.add(connection + root.val);
if(root.left != null)
searchTree(res, root.left, connection + root.val + "->");
if(root.right != null)
searchTree(res, root.right, connection + root.val + "->");
}
}