For example:
Given binary tree
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[[15,7],[9,20],[3] ]
Approach:
1.Add root to queue
2.pop item in queue and add left and right nodes of that item to queue.now add value of popped to a temporary array
3.repeat the above step len(queue) no of times
4.Add that temporary to result array
5.if size of queue !=0 go to step 2
6.return reversed result array
Python Code:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def levelOrderBottom(self, root):
if not root :
return []
queue = []
result = []
queue.append(root)
while len(queue)>0:
temp = []
for i in range(len(queue)):
node = queue.pop(0)
temp.append(node.val)
if node.left!=None: queue.append(node.left)
if node.right!=None: queue.append(node.right)
result.insert(0,temp)
return result
Try Quoeston Here
0 Comments