257. Binary Tree Paths

来源:互联网 发布:eclipse怎么写java程序 编辑:程序博客网 时间:2024/06/05 23:04

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"]

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.


Solution:

Tips:

tree, recursion


Java Code:

/** * 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> result = new ArrayList<>();        if (null == root) {            return result;        }                binaryTreePaths(root, "", result);                return result;    }        // root cann't be null    private void binaryTreePaths(TreeNode root, String str, List<String> result) {        if (root.left == null && root.right == null) {            result.add(str + root.val);            return;        }                str = str + root.val + "->";        if (root.left != null) {            binaryTreePaths(root.left, str, result);        }                if (root.right != null) {            binaryTreePaths(root.right, str, result);        }    }}


0 0