257. Binary Tree Paths

来源:互联网 发布:目前常见数据库有哪些 编辑:程序博客网 时间:2024/05/30 05:41

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.

/** * 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) {        StringBuilder data = new StringBuilder();List<String> re = new ArrayList<String>();if(root==null)    return re;fun(root, data, re);return re;    }    static void fun(TreeNode root, StringBuilder data, List<String> re) {if(root!=null&&(root.left==null&&root.right==null)){data.append(root.val);re.add(data.toString());while (data.length() > 0 && data.charAt(data.length() - 1) != '>')data.deleteCharAt(data.length()-1);return;}data.append(root.val).append("->");if(root.left!=null)fun(root.left, data, re);if(root.right!=null)fun(root.right, data, re);do{data.deleteCharAt(data.length()-1);}while (data.length() > 0 && data.charAt(data.length() - 1) != '>');}}


0 0