Skip to content

102. 二叉树的层次遍历 #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jotoy opened this issue Feb 22, 2020 · 0 comments
Open

102. 二叉树的层次遍历 #32

jotoy opened this issue Feb 22, 2020 · 0 comments

Comments

@jotoy
Copy link
Owner

jotoy commented Feb 22, 2020

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

解法:用BFS的思想

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

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return None
        queue = []
        queue.insert(0, root)
        res = []
        level = 0
        while queue:
            length = len(queue)
            res.append([])
            for _ in range(length):
                cur = queue.pop()
                res[level].append(cur.val)
                if cur.left:
                    queue.insert(0,cur.left)
                if cur.right:
                    queue.insert(0,cur.right)
            level+=1
        return res
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant