Reverse Level Order Traversal of a Binary Tree (Leetcode 107)
Trick: Simply insert the reverse of temp arrays at each stage and reverse the ans array in the end.
Problem Link: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
class Solution:
def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
if(root is None):
return []
ans=[]
q=[root]
while(len(q)>0):
temp=[]
for i in range(len(q)):
currnode=q.pop()
if(currnode.right):
q.insert(0,currnode.right)
if(currnode.left):
q.insert(0,currnode.left)
temp.append(currnode.val)
ans.append(temp[::-1])
return ans[::-1]
PreviousLevel Order Traversal of a Binary Tree (Leetcode 102)NextZig-Zag Level Order Traversal of a Binary Tree (Leetcode 103)
Last updated