[LeetCode] Binary Tree Paths
来源:互联网 发布:淘宝v2贷款怎么搞 编辑:程序博客网 时间:2024/06/06 02:13
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”]
解题思路
先序遍历,递归的过程中保存路径,遇到叶子节点时将路径加入结果集。
实现代码
Java:
// Runtime: 3 ms/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { private List<String> paths = new ArrayList<String>(); public List<String> binaryTreePaths(TreeNode root) { if (root != null) { traverse(root, String.valueOf(root.val)); } return paths; } private void traverse(TreeNode root, String path) { if (root.left == null && root.right == null) { paths.add(path); } if (root.left != null) { traverse(root.left, path + "->" + root.left.val); } if (root.right != null) { traverse(root.right, path + "->" + root.right.val); } }}
1 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
- ASCII表、ASCII扩展表
- 建立网络连接的基本步骤及NSJSONSerialization(苹果自带)——JSON解析
- 知乎下拉刷新SwipeRefreshLayout下拉刷新用法类似知乎下拉刷新
- iOS开发-前言篇C-指针以、结构体指针、作用域
- mjpg-streamer在pcduino上的应用
- [LeetCode] Binary Tree Paths
- SpringMVC注解之看一眼
- windows安装kivy最少走弯路的方法
- button按钮大小
- c语言 参数个数可变函数
- lightoj1245 - Harmonic Number (II)【数学】
- 七种常见排序算法的总结
- C/C++内存泄漏及检测
- c语言 动态内存分配