二叉树的广度优先搜索

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None        
    def bfs(self,root):
        if not root:
            return []
        p = [root]
        res = []
        while p:
            q = []
            for i in p:
                res.append(i.val)
                if i.left: q.append(i.left)
                if i.right: q.append(i.right)
            p = q
        return res

你可能感兴趣的:(二叉树的广度优先搜索)