Created
January 20, 2016 07:31
-
-
Save Shaunwei/4132d5fafbd0001f785c to your computer and use it in GitHub Desktop.
Binary Tree Level Order Traversal. Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Definition of TreeNode: | |
| class TreeNode: | |
| def __init__(self, val): | |
| self.val = val | |
| self.left, self.right = None, None | |
| """ | |
| import collections | |
| class Solution: | |
| """ | |
| @param root: The root of binary tree. | |
| @return: Level order in a list of lists of integers | |
| """ | |
| def levelOrder(self, root): | |
| if not root: | |
| return [] | |
| # # BFS | |
| # # 2 queues | |
| q1 = [] | |
| q1.append(root) | |
| q2 = [] | |
| ret = [] | |
| while q1: | |
| lvl = [] | |
| while q1: | |
| node = q1.pop(0) | |
| if node.left: | |
| q2.append(node.left) | |
| if node.right: | |
| q2.append(node.right) | |
| lvl.append(node.val) | |
| q1 = q2 | |
| q2 = [] | |
| ret.append(lvl) | |
| return ret | |
| class Solution1: | |
| """ | |
| @param root: The root of binary tree. | |
| @return: Level order in a list of lists of integers | |
| """ | |
| def levelOrder(self, root): | |
| if not root: | |
| return [] | |
| # # BFS | |
| # # 1 queue | |
| queue = collections.deque() | |
| queue.append(root) | |
| ret = [] | |
| while queue: | |
| size = len(queue) | |
| lvl = [] | |
| for _ in xrange(size): | |
| node = queue.popleft() | |
| if node.left: | |
| queue.append(node.left) | |
| if node.right: | |
| queue.append(node.right) | |
| lvl.append(node.val) | |
| ret.append(lvl) | |
| return ret | |
| class Solution2: | |
| """ | |
| @param root: The root of binary tree. | |
| @return: Level order in a list of lists of integers | |
| """ | |
| def levelOrder(self, root): | |
| if not root: | |
| return [] | |
| # DFS | |
| lvls = collections.defaultdict(list) | |
| self.dfs(root, 0, lvls) | |
| ret = [] | |
| for _, values in sorted(lvls.items()): | |
| ret.append(values) | |
| return ret | |
| def dfs(self, root, cur_lvl, lvls): | |
| if root: | |
| lvls[cur_lvl].append(root.val) | |
| self.dfs(root.left, cur_lvl + 1, lvls) | |
| self.dfs(root.right, cur_lvl + 1, lvls) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment