leetcode 257. Binary Tree Paths
来源:互联网 发布:网络综艺节目受众人群 编辑:程序博客网 时间:2024/05/21 07:50
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"]这道题蛮简单的。
public List<String> binaryTreePaths(TreeNode root) {List<String> list=new ArrayList<String>();if(root==null){return list;}helper(root, list, new ArrayList<Integer>());return list;}public void helper(TreeNode node,List<String> list,List<Integer> currentPath){currentPath.add(node.val);if(node.left==null&&node.right==null){list.add(getString(currentPath));}if(node.left!=null){helper(node.left, list, currentPath);}if(node.right!=null){helper(node.right, list, currentPath);}currentPath.remove(currentPath.size()-1);}public String getString(List<Integer> currentPath){String result=currentPath.get(0)+"";for(int i=1;i<currentPath.size();i++){result+="->"+currentPath.get(i);}return result;}有大神也用了递归,并且运用了函数参数是string,传的是值,不是引用的特性,就不用在方法最后remove当前元素了。
public List<String> binaryTreePaths(TreeNode root) { List<String> answer = new ArrayList<String>(); if (root != null) searchBT(root, "", answer); return answer;}private void searchBT(TreeNode root, String path, List<String> answer) { if (root.left == null && root.right == null) answer.add(path + root.val); if (root.left != null) searchBT(root.left, path + root.val + "->", answer); if (root.right != null) searchBT(root.right, path + root.val + "->", answer);}
阅读全文
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
- 使用toggle()方法进行显示隐藏
- 集合(3)张飞
- 考察Hadoop的底层rpc通信(二)
- Java经典算法题(五)
- 使用Java蓝牙无线通讯技术API概述
- leetcode 257. Binary Tree Paths
- python pydub 用法 (2)
- Sticks POJ
- javaee学习日记之java基础之类和对象
- (三)libevent源文件结构
- JAVA中的反射机制
- memcached会话共享+分布式+Thinkphp5
- Struts2 值栈和ognl
- zookeeper安装(单节点)及基本操作