【leetcode】257. Binary Tree Paths
来源:互联网 发布:中国人口密度数据 编辑:程序博客网 时间:2024/04/27 16:45
题目要求:
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"]给一颗二叉树,返回根节点到叶子结点的路径
思路:
用一个map储存每个结点的路径
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> result = new LinkedList<String>(); if(root==null) { return result; } //定义一个stack用来遍历结点 Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); //map 的key是当前结点,val是路径 Map<TreeNode,String> path = new HashMap<TreeNode,String>(); path.put(root,root.val+""); while(!stack.isEmpty()) { TreeNode temp = stack.pop(); if(temp.left==null&&temp.right==null) { result.add(path.get(temp)); } if(temp.left!=null) { stack.push(temp.left); path.put(temp.left,path.get(temp)+"->"+temp.left.val+""); } if(temp.right!=null) { stack.push(temp.right); path.put(temp.right,path.get(temp)+"->"+temp.right.val+""); } } return result; }}
0 0
- [leetcode] 257. Binary Tree Paths
- 257. Binary Tree Paths LeetCode
- 【LeetCode】257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- LeetCode *** 257. Binary Tree Paths
- leetcode 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- Leetcode 257. Binary Tree Paths
- LeetCode-257.Binary Tree Paths
- 【leetcode】257. Binary Tree Paths
- [Leetcode]257. Binary Tree Paths
- LeetCode - 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- [leetcode] 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- 257.[Leetcode]Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- leetcode 257. Binary Tree Paths
- JSP页面根据后台传值不同显示不同内容
- Android AlertDialog自定义布局
- Jetty 的工作原理以及与 Tomcat 的比较
- 从0开始搭建自己的个人网站教程(一)域名注册
- cell点击更多当前变高
- 【leetcode】257. Binary Tree Paths
- Citymaker open datasource throws a exception
- JAVA获取字符串首字拼音和全拼
- 行人检测综述
- 关于ibatis出现AutoResultMap错误的问题
- hdu_2046
- checkbox设置复选框的只读效果不让用户勾选
- 线性判别分析(Linear Discriminant Analysis, LDA) 算法分析与代码
- tomcat 的功能及优化