![](https://www.dazhuanlan.com/webchat.jpg)
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"]
2. Analysis
3. Solution(s)
Recursive implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class : def binaryTreePaths(self, root): if not root: return list() result = [ str(root.val)+"->" + path for path in self.binaryTreePaths(root.left)] result += [ str(root.val)+"->" + path for path in self.binaryTreePaths(root.right)] return result or [str(root.val)]
|
Iterative implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
def binaryTreePaths(self, root): if not root: return list() res = [] stack = [] path_stack = [] stack.append(root) while len(stack)>0: tmp = stack.pop() if(tmp.left): print "D:", tmp.val stack.append(tmp.left) if(tmp.right): print "D:", tmp.val stack.append(tmp.right) if(not tmp.left and not tmp.right): print "leaf:", tmp.val return res
|
近期评论