《leetCode》:Binary Tree Paths
来源:互联网 发布:爱淘宝怎么注册账号 编辑:程序博客网 时间:2024/06/01 07:55
题目
Given a binary tree, return all root-to-leaf paths.For example, given the following binary tree: 1 / \2 3 \ 5All root-to-leaf paths are:["1->2->5", "1->3"]
思路
利用递归即可解决。求当前节点的左子树和右子树的路径,然后将当前节点加入到这些路径的前面。
实现代码如下:
package com.wrh.leetcode; import java.util.ArrayList; import java.util.List; public class BinaryTreePaths { public List<String> binaryTreePaths(TreeNode root) { List<List<Integer>> res = binaryTreePathHelper(root); List<String> paths = new ArrayList<String> (); for(List<Integer> list : res){ StringBuilder sb = new StringBuilder(); for(int i=0;i<list.size();i++){ if(i==list.size()-1){ sb.append(list.get(i)); } else{ sb.append(list.get(i)).append("->"); } } paths.add(sb.toString()); } return paths; } private List<List<Integer>> binaryTreePathHelper(TreeNode root) { List<List<Integer>> res = new ArrayList<List<Integer>>() ; if(root==null){ return res; } if(root.left==null&&root.right==null){//叶子节点 List<Integer> list = new ArrayList<Integer>(); list.add(root.val); res.add(list); return res; } else { List<List<Integer>> leftRes = binaryTreePathHelper(root.left) ; List<List<Integer>> rightRes = binaryTreePathHelper(root.right) ; for(List<Integer> list : leftRes){ list.add(0,root.val); res.add(list); } for(List<Integer> list : rightRes){ list.add(0,root.val); res.add(list); } return res; } } public static void main(String[] args){ TreeNode t = new TreeNode(3); TreeNode t2 = new TreeNode(5); TreeNode t3 = new TreeNode(6); t.left = t2 ; t.right = t3 ; List<String> list = new BinaryTreePaths().binaryTreePaths(t); for(String str:list){ System.out.println(str); } } }
0 0
- Leetcode: Binary Tree Paths
- [LeetCode] Binary Tree Paths
- [Leetcode]Binary Tree Paths
- leetcode:Binary Tree Paths
- [leetcode] Binary Tree Paths
- Leetcode: Binary Tree Paths
- LeetCode:Binary Tree Paths
- leetcode Binary Tree Paths
- leetcode Binary Tree Paths
- LeetCode:Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode || Binary Tree Paths
- *LeetCode-Binary Tree Paths
- Binary Tree Paths -- leetcode
- LeetCode---Binary Tree Paths
- leetcode-Binary Tree Paths
- 嵌入式开发第二日(man 手册、linux基本命令、vim编辑器、代码编译过程、编译工具、基本数据类型、控制流)
- 乐乐音乐-KSC歌词图片生成器
- UVa 1347
- Ext初学
- 丑数
- 《leetCode》:Binary Tree Paths
- 100. Same Tree--LeetCode Record
- 【usaco 2012 Nov Bronze】找奶牛Find the Cow!
- uva 12169 - Disgruntled Judge(暴力or欧几里得 )
- dos界面操作mysql讲解
- Android 学习之路
- TYVJ 2009「Poetize8」Lagoon
- Android开源项目 个性化控件(View)
- Appium 安装配置(Windows)