二叉树的广度优先搜索

2018-08-25  本文已影响0人  小歪与大白兔
# 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
上一篇下一篇

猜你喜欢

热点阅读