首页 > 其他 > 详细

257. Binary Tree Paths

时间:2016-07-15 12:53:53      阅读:236      评论:0      收藏:0      [点我收藏+]

题目:

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"]

链接: http://leetcode.com/problems/binary-tree-paths/

一刷

刚刚复习了树的后序遍历, 先尝试用iterative方法,但是performance并不是很理想

 1 class Solution:
 2     # @param {TreeNode} root
 3     # @return {string[]}
 4     def binaryTreePaths(self, root):
 5         if not root:
 6             return []
 7         path = [root]
 8         prev = None
 9         cur = path[-1]
10         result = []
11         while path:
12             cur = path[-1]
13             if not prev or prev.left == cur or prev.right == cur:
14                 if cur.left:
15                     path.append(cur.left)
16                 elif cur.right:
17                     path.append(cur.right)
18                 else:
19                     result.append(->.join([str(a.val) for a in path]))
20                     path.pop()
21             elif cur.left == prev:
22                 if cur.right:
23                     path.append(cur.right)
24                 else:
25                     path.pop()
26             elif cur.right == prev:
27                 path.pop()
28             prev = cur
29         return result

其实与树的后序遍历唯一区别是第19行,如果没有19行,就是完全的树的后序遍历,也就可以refactor到此链接里的alternative解法,但是正是有了这一行,就不能refactor。原因是,我们需要把所有节点都pop,但是只有叶节点需要放进result。

下一次需要用recursive解法,希望performance变好。

257. Binary Tree Paths

原文:http://www.cnblogs.com/panini/p/5673069.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!