- Binary Tree Level Order Traversal
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
return its level order traversal as:
[[3],[9,20],[15,7]]
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import queue
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
q=queue.Queue()
if not root:
return []
q.put(root)
res=[]
level=0
while(not q.empty()):
num=q.qsize()
res.append([])
for i in range(num):
node=q.get()
res[level].append(node.val)
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
level+=1
return res
- Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
return its bottom-up level order traversal as:
[[15,7],[9,20],[3]]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import queue
class Solution:
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
res=[]
q=queue.Queue()
q.put(root)
num=1
level=0
while(not q.empty()):
res.append([])
for i in range(num):
node=q.get()
num-=1
res[level].append(node.val)
if node.left:
q.put(node.left)
num+=1
if node.right:
q.put(node.right)
num+=1
level+=1
return res[::-1]