Leetcode binary tree level order traversal
This is a binary tree hierarchy traversal. The simplest and most intuitive method for hierarchy traversal is BFs. Therefore, we only need to maintain a queue. The elements in the queue need to record the content of the node and the layer where the node is located, and then retrieve the nodes from the queue for expansion.
# Definition for a binary tree node# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: # @param root, a tree node # @return a list of lists of integers def levelOrder(self, root): if(root == None): return [] queue = [] queue.append((0, root)) ans = [] cur = 0 cur_nodes = [] while len(queue) != 0: level, fa = queue.pop(0) if(level == cur): cur_nodes.append(fa.val) else: ans.append(cur_nodes) cur_nodes = [] cur_nodes.append(fa.val) cur = level if fa.left != None: queue.append((level+1, fa.left)) if fa.right != None: queue.append((level+1, fa.right)) ans.append(cur_nodes) return ans
Leetcode tree related problems (update continuously)