题目
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 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; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
}
}
分析
如果当前结点没有左树和右树,那么就把之前的string拼在一起,并且将中间的空格替换成->,如果有左树,就迭代左树;如果有右树,就迭代右树。
解答
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
if(root == null){
return list;
}
iterator(root,list,"");
return list;
}
public void iterator(TreeNode root,List<String> list,String str){
str = str + " "+root.val;
if(root.left == null && root.right == null){
list.add(str.trim().replace(" ","->"));
}
if(root.left != null){
iterator(root.left,list,str);
}
if(root.right != null){
iterator(root.right,list,str);
}
}
}