102. Binary Tree Level Order Traversal
https://leetcode.com/problems/binary-tree-level-order-traversal/
js
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
function levelOrder(root) {
if (!root) {
return []
}
const result = []
let current = [root]
while (current.length) {
let vals = []
let next = []
current.forEach(node => {
vals.push(node.val)
if (node.left) {
next.push(node.left)
}
if (node.right) {
next.push(node.right)
}
})
result.push(vals)
current = next
}
return result
}
py
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
current, result = [root], []
while current:
vals, nxt = [], []
for node in current:
vals.append(node.val)
if node.left:
nxt.append(node.left)
if node.right:
nxt.append(node.right)
result.append(vals)
current = nxt
return result
go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
result := [][]int{}
current := []*TreeNode{root}
for len(current) > 0 {
var vals []int
var next []*TreeNode
for _, node := range current {
vals = append(vals, node.Val)
if node.Left != nil {
next = append(next, node.Left)
}
if node.Right != nil {
next = append(next, node.Right)
}
}
result = append(result, vals)
current = next
}
return result
}