题目来源:LeetCode: 257. 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”]
思路
- 二叉树的遍历:先序遍历,递归调用
- 解决好走过路径的记录和回退
- C语言处理字符的操作不太便捷,试着用Python写这道题
源码
1 | //257. Binary Tree Paths |
运行结果:
209 / 209 test cases passed.
Status: Accepted
Runtime: 60 -> 58 -> 50 -> 48 ms
Submitted: 13 minutes agoYou are here! Your runtime beats 64.24% of csubmissions.
总结
- 递归的方式遍历二叉树,调整节点输出的位置便实现了不同的遍历方式
- Python的执行效率相比C还是差了不少,C的话应该在10ms内
- Python写的好处是List可以实现栈的功能,确实方便
- 改进三版本后代码跑48ms,看别人Python也有写到40ms左右的,如何实现的?
- 删除执行一次的if判断
- 增加if(node.left is not None),避免进入空的循环
- 字符串累加放在一起做,避免多条指令