您的位置:首页 > 其它

找出二叉树所有到叶子节点的路径

2016-06-09 23:21 225 查看
import java.util.*;

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<>();
if (root == null)
return list;

if (root.left == null && root.right == null)
list.add(root.val + "");

for (String path : binaryTreePaths(root.left))
list.add(root.val + "->" + path);

for (String path : binaryTreePaths(root.right))
list.add(root.val + "->" + path);
return list;
}

public static void main(String[] args) {
TreeNode one = new TreeNode(1);
TreeNode two = new TreeNode(2);
TreeNode three = new TreeNode(3);
TreeNode five = new TreeNode(5);
one.left = two;
one.right = three;
two.right = five;

new Solution().binaryTreePaths(one).forEach(System.out::println);
}
}


[参考资料]https://leetcode.com/discuss/55451/clean-solution-accepted-without-helper-recursive-function
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息