首页 > 代码库 > LeetCode-Binary Tree Paths
LeetCode-Binary Tree Paths
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.
Solution:
/** * 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> resList = new LinkedList<String>(); StringBuilder builder = new StringBuilder(); binaryTreePaths(root,builder,resList); return resList; } public void binaryTreePaths(TreeNode cur, StringBuilder builder, List<String> resList){ if (cur==null){ return; } builder.append(cur.val); if (cur.left==null && cur.right==null){ resList.add(builder.toString()); return; } builder.append("->"); int len = builder.length(); binaryTreePaths(cur.left,builder,resList); builder.setLength(len); binaryTreePaths(cur.right,builder,resList); }}
LeetCode-Binary Tree Paths
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。