Created
January 27, 2019 02:41
-
-
Save Anirudhk94/4a49179d26f6f5f69e5f08cfe0d5941e to your computer and use it in GitHub Desktop.
This file contains 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
from collections import defaultdict | |
from collections import deque | |
# Definition for a binary tree node. | |
# class TreeNode: | |
# def __init__(self, x): | |
# self.val = x | |
# self.left = None | |
# self.right = None | |
class Solution: | |
def verticalOrder(self, root): | |
""" | |
:type root: TreeNode | |
:rtype: List[List[int]] | |
""" | |
result = [] | |
if root is None: | |
return result | |
map = defaultdict(list) | |
q = deque() | |
index = deque() | |
mini = 0 | |
q.append(root) | |
index.append(0) | |
while(q): | |
curr = q.popleft() | |
idx = index.popleft() | |
map[idx].append(curr.val) | |
if curr.left : | |
q.append(curr.left) | |
index.append(idx - 1) | |
if curr.right : | |
q.append(curr.right) | |
index.append(idx + 1) | |
mini = min(mini, idx) | |
while(map[mini]): | |
result.append(map.get(mini)) | |
mini += 1 | |
return result | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment