首页 > 其他 > 详细

[LeetCode] 257. Binary Tree Paths_ Easy tag: DFS

时间:2018-07-14 00:03:55      阅读:178      评论:0      收藏:0      [点我收藏+]

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   2     3
   5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

思路为DFS, 只是append进入stack的时候一并append进入当前的path即可.

1. Constraints
1) can be empty

2. Ideas
DFS T: O(n) S: O(n)
1) edge case
2) stack = [(root, str(root.val))]
3) DFS, if leaf, ans.append(path)
4)return ans

3. Codes
3.1) iterable
 1 class Solution:
 2     def path(self, root):
 3         if not root: return []
 4         ans, stack = [], [(root, str(root.val))]
 5         while stack
 6             node, path = stack.pop()
 7             if not node.left and not node.right:
 8                 ans.append(path)
 9             if node.right:
10                 stack.append((node.right, path + "->" + node.right.val))
11             if node.left:
12                 stack.append((node.left, path + "->" + node.left.val))
13         return ans

 

3.2) Recursive

 1 class Solution:
 2     def path(self, root):
 3         def helper(root, path, ans):
 4             path += str(root.val)
 5             if not root.left and not root.right:
 6                 ans.append(path)
 7             if root.left:
 8                 stack.append((root.left, path + "->", ans))
 9             if root.right:
10                 stack.append((root.right, path + "->", ans))
11         if not root: return []
12         ans = []
13         helper(root, "", ans)
14         return ans

 

4.. Test cases

1) empty

2)  1

3) 

   1
 /   2     3
   5

[LeetCode] 257. Binary Tree Paths_ Easy tag: DFS

原文:https://www.cnblogs.com/Johnsonxiong/p/9307968.html

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