LeetCode 257. Binary Tree Paths

来源:互联网 发布:mac 任务管理工具 编辑:程序博客网 时间:2024/06/05 02:00

description:
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”]

解题思路:
题目并不难,可以直接使用divide conquer的方法直接进行求解

/** * 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) {        // using divide conquer algorithm        List<String> list = new ArrayList<>();        if (root == null) {            return list;        }        List<String> left = binaryTreePaths(root.left);        List<String> right = binaryTreePaths(root.right);        for (String str : left) {            list.add(root.val + "->" + str);        }        for (String str : right) {            list.add(root.val + "->" + str);        }        if (list.size() == 0) {            list.add("" + root.val);        }        return list;    }}
0 0