首页 > 代码库 > leetcode tree related problems (update continuously)

leetcode tree related problems (update continuously)

leetcode Binary Tree Level Order Traversal

这道题是要进行二叉树的层次遍历,对于层次遍历,最简单直观的办法就是进行BFS。于是我们只需要维护一个队列就可以了,队列里面的元素需要记录该节点的内容和节点所在的层,依次从队列中取出节点进行扩展就可以了。

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class 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)