Leetcode_257_Binary Tree Paths
来源:互联网 发布:淘宝网买家地域解读 编辑:程序博客网 时间:2024/06/03 21:31
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/49432057
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"]
思路:
(1)题意为给定一棵树,找出所有从根到叶子节点的路径。
(2)该题实为树的深度优先遍历。本题是使用递归的方法来进行求解的,从根节点开始,若左子树不为空,则遍历左子树,若左子树的左孩子不为空,则遍历左孩子,否则遍历右孩子.....直到遍历完最后一个叶子节点为止。使用非递归算法,则需要设定一个栈来保存左右子树,也很好实现,这里不累赘了。
(3)详情见下方代码。希望本文对你有所帮助。
package leetcode;import java.util.ArrayList;import java.util.List;import leetcode.utils.TreeNode;public class Binary_Tree_Paths {public static void main(String[] args) {TreeNode r = new TreeNode(1);TreeNode r1 = new TreeNode(2);TreeNode r2 = new TreeNode(3);TreeNode r3 = new TreeNode(5);r.left = r1;r.right = r2;r1.right = r3;binaryTreePaths(r);}public static List<String> binaryTreePaths(TreeNode root) {List<String> result = new ArrayList<String>();if (root != null) {getpath(root, String.valueOf(root.val), result);}return result;}private static void getpath(TreeNode root, String valueOf,List<String> result) {if (root.left == null && root.right == null)result.add(valueOf);if (root.left != null) {getpath(root.left, valueOf + "->" + root.left.val, result);}if (root.right != null) {getpath(root.right, valueOf + "->" + root.right.val, result);}}}
1 0
- Leetcode_257_Binary Tree Paths
- [leetcode][tree] Binary Tree Paths
- Print tree paths
- Binary Tree Paths
- Leetcode: Binary Tree Paths
- [LeetCode] Binary Tree Paths
- [Leetcode]Binary Tree Paths
- leetcode:Binary Tree Paths
- Binary Tree Paths
- [leetcode] Binary Tree Paths
- 257 Binary Tree Paths
- Binary Tree Paths
- [LeetCode257] Binary Tree Paths
- Binary Tree Paths
- Binary Tree Paths
- Leetcode: Binary Tree Paths
- LeetCode:Binary Tree Paths
- leetcode Binary Tree Paths
- Java教程例题3.2
- 属性之get,set
- JAVA 命令行运行java项目
- 利用BOOST,解释JSON
- 自定义泛型类型和方法
- Leetcode_257_Binary Tree Paths
- 【2015/10/25】C 学习日志_Day10 运算符
- 网站外部链接(读书笔记)
- 线段树+离散化操作(poj 2528)
- editplus生成页面框架
- svg动画的学习相关
- Android Scrollview+Listview 实现不同条目点赞并计数功能及原理分析(2)
- 子序列
- Java面试题全集(上)