leetcode--Binary Tree Paths
来源:互联网 发布:mysql高并发优化方案 编辑:程序博客网 时间:2024/04/29 21:20
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”]
解:
用递归解最方便,但写法上稍有些不同
一.
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ return self.stringPath(root) def stringPath(self,root): li=[] if root is None: return [] elif not(root.left or root.right): return [str(root.val)] else: left=self.stringPath(root.left) right=self.stringPath(root.right) for sl in range(len(left)): left[sl]=str(root.val)+'->'+left[sl] for rl in range(len(right)): right[rl]=str(root.val)+'->'+right[rl] return left+right
二.
public List<String> binaryTreePaths(TreeNode root) { List<String> answer = new ArrayList<String>(); if (root != null) searchBT(root, "", answer); return answer;}//这里传递一个String path参数表示在这之前的路径信息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: Binary Tree Paths
- [LeetCode] Binary Tree Paths
- [Leetcode]Binary Tree Paths
- leetcode:Binary Tree Paths
- [leetcode] Binary Tree Paths
- Leetcode: Binary Tree Paths
- LeetCode:Binary Tree Paths
- leetcode Binary Tree Paths
- leetcode Binary Tree Paths
- LeetCode:Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode || Binary Tree Paths
- *LeetCode-Binary Tree Paths
- Binary Tree Paths -- leetcode
- LeetCode---Binary Tree Paths
- leetcode-Binary Tree Paths
- 解析几何:第六章 二次曲面(1)球面 椭球面 双曲面
- 创建守护进程并且接收信号
- POJ2391:Ombrophobic Bovines floyd+二分答案+最大流
- Android自动化测试(UiAutomator)介绍与学习
- C/CPP点滴积累—#define ,typedef
- leetcode--Binary Tree Paths
- 一步步创建自己的 iOS 框架
- 简易 文章发布系统——前台界面
- Android Studio 更换国内源下载依赖库
- 解析几何:第六章 二次曲面(2)抛物面 二次锥面 柱面 一般二次曲面
- mutex和spin lock的区别
- mysql----快速删除数据表(drop,truncate,delete)
- Oracle - 数据库字符集的查询
- 支持向量机SVM(二)