Easy-题目53:257. Binary Tree Paths
来源:互联网 发布:弹弹安卓版吉他软件 编辑:程序博客网 时间:2024/05/29 04:53
题目原文:
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”]
题目大意:
给出一个二叉树,输出所有从根节点到叶子节点的路径。
题目分析:
遍历即可,注意每次向左右子树搜索的时候,把当前路径一直带在函数参数里面。
源码:(language:java)
public class Solution { List<String> res = new ArrayList<String>(); public List<String> binaryTreePaths(TreeNode root) { if(root != null) findPaths(root,String.valueOf(root.val)); return res; } private void findPaths(TreeNode n, String path){ if(n.left == null && n.right == null) res.add(path); if(n.left != null) findPaths(n.left, path+"->"+n.left.val); if(n.right != null) findPaths(n.right, path+"->"+n.right.val); }}
成绩:
3ms,beats 27.22%,众数3ms,47.28%.
0 0
- Easy-题目53:257. Binary Tree Paths
- 257. Binary Tree Paths [easy] (Python)
- Leetcode 257. Binary Tree Paths (Easy) (cpp)
- LeetCode解题报告 257. Binary Tree Paths [easy]
- Easy 257题 Binary Tree Paths
- leetcode 257[easy]-----Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- A strange lift
- Easy-题目52:14. Longest Common Prefix
- 3. Longest Substring Without Repeating Characters
- CSS的继承性,特殊性和层叠性
- SDNU1332 矩阵交换
- Easy-题目53:257. Binary Tree Paths
- 递归
- Easy-题目54:234. Palindrome Linked List
- 虚表解析以及构造函数为什么不能是虚函数
- JAVA学习笔记整理四(异常处理)
- java int 与byte互转(转)
- 点击元素使其在毫秒内从不透明变为透明
- hdu 3879(最小割模型求解最大权闭合图)
- 抽象