Binary Tree Paths
2015-10-22 22:26
204 查看
输出二叉树的寻叶路径
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"]
遍历二叉树的时候,每当寻到叶结点,把路径装进结果里
输出:
0->1->3 0->1->4->7 0->2->5 0->2->6
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"]
遍历二叉树的时候,每当寻到叶结点,把路径装进结果里
package com.rust.datastruct; import java.util.ArrayList; import java.util.List; /** * judging * 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"] */ class BinaryTreePathsSolution { List<String> res = new ArrayList<String>(); public List<String> binaryTreePaths(TreeNode root) { if (root != null) track(root, root.val + "");/* String.valueOf(root.val)*/ return res; } private void track(TreeNode n, String path){ if (n.left == null && n.right == null) res.add(path); if (n.left != null) track(n.left, path + "->" + n.left.val);/* continue tracking */ if (n.right != null) track(n.right, path + "->" + n.right.val); } } /** * Test main */ public class BinaryTreePaths { public static void main(String args[]) { TreeNode root = new TreeNode(0); TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); TreeNode node3 = new TreeNode(3); TreeNode node4 = new TreeNode(4); TreeNode node5 = new TreeNode(5); TreeNode node6 = new TreeNode(6); TreeNode node7 = new TreeNode(7); root.left = node1; root.right = node2; node1.left = node3; node1.right = node4; node2.left = node5; node2.right = node6; node4.right = node7; BinaryTreePathsSolution solution = new BinaryTreePathsSolution(); List<String> res = solution.binaryTreePaths(root); for (int i = 0;i < res.size();i++){ System.out.print(res.get(i) + " "); } System.exit(0); } }
输出:
0->1->3 0->1->4->7 0->2->5 0->2->6
相关文章推荐
- 刷新页面
- [转]android 自定义圆形imageview控件
- 获得浏览器窗口滚动条位置
- ScrollView滚动到底部使用的scrollTo和fullScroll方法的异同
- Android 中 Activity 启动模式
- JPA关联关系
- 软工二
- WMvare workstation创建共享磁盘
- java高并发,如何解决,什么方式解决
- HDOJ 题目2151 Worm(DP水)
- PullToRefreshListView调用onRefreshComplete方法 无法取消刷新的bug
- Hashtable 和 HashMap的区别
- 基于Lucene的全文搜索——Solr
- C语言存储模型小议
- HDU 5462 Manors (2015年沈阳赛区网络赛M题)
- Android软件开发之获取通讯录联系人信息
- hibernate原理解析
- WebService客户端设置缓冲大小问题
- 2015年10月22日总结
- eclipse调用两个控制台进行调试