Leetcode_257_Binary Tree Paths
2015-10-26 23:25
337 查看
本文是在学习中的总结,欢迎转载但请注明出处: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);
}
}
}
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);
}
}
}
相关文章推荐
- Java面试题全集(上)
- Leetcode_257_Binary Tree Paths
- 子序列
- tp框架搭建
- 浏览器中JavaScript执行原理
- Android利用Fiddler进行网络数据抓包
- 怎么查询NSLog中每个数据类型对应的占位符
- Windows 下实现线程局部存储
- 网站外部链接(读书笔记)
- 自定义泛型类型和方法
- 利用BOOST,解释JSON
- 【2015/10/25】C 学习日志_Day10 运算符
- UML学习笔记之状态图
- Bank,我只是来完成作业的
- 为何在新建的client中无法用sap*登录?
- Daily Srum 10.26
- 《Intel汇编第5版》 汇编减法程序
- 乘法口诀
- 属性之get,set
- Java教程例题3.2