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"]
给定一个二叉树,输出从根到叶子节点的路径。用递归来完成,代码如下:
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> list = new ArrayList<String>();
if(root == null) return list;
getPath(root, String.valueOf(root.val), list);
return list;
}
public void getPath(TreeNode root, String s, List<String> list) {
if(root.left == null && root.right == null)
list.add(s);
if(root.left != null)
getPath(root.left, s + "->" + root.left.val, list);
if(root.right != null)
getPath(root.right, s + "->" + root.right.val, list);
}
}