java
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
if (root == null) {
return res;
}
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
List<Integer> level = new LinkedList<>();
for (int i = 0; i < size; i++) {
TreeNode current = q.poll();
level.add(current.val);
if (current.left != null) {
q.add(current.left);
}
if (current.right != null) {
q.add(current.right);
}
}
res.add(level);
}
return res;
}
go
func levelOrder(root *TreeNode) [][]int {
res := [][]int{}
if root == nil {
return res
}
q := []*TreeNode{root}
for len(q) > 0 {
level := []int{}
size := len(q)
for i := 0; i < size; i++ {
current := q[0]
level = append(level, current.Val)
q = q[1:]
if current.Left != nil {
q = append(q, current.Left)
}
if current.Right != nil {
q = append(q, current.Right)
}
}
res = append(res, level)
}
return res
}
c++
#include <iostream>
#include "build_tree.cpp"
#include <queue>
using namespace std;
class LevelTraverse {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res = {};
if (!root) {
return res;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
int size = q.size();
vector<int> level;
for (int i = 0; i < size; i++) {
TreeNode* current = q.front();
q.pop();
level.push_back(current->val);
if (current->left) {
q.push(current->left);
}
if (current->right) {
q.push(current->right);
}
}
res.push_back(level);
}
return res;
}
};
int main() {
BuildTree build;
LevelTraverse test;
vector<int> preorder = {1, 2, 5, 4, 6, 7, 3, 8, 9};
vector<int> inorder = {5, 2, 6, 4, 7, 1, 8, 3, 9};
TreeNode* root = build.buildTreeFromPreAndIn(preorder, inorder);
vector<vector<int>> res = test.levelOrder(root);
for (vector<int>item : res) {
for (int i : item) {
cout<<i;
}
cout<<endl;
}
return 0;
}
python
from typing import Optional, List
from data_algo.algo.tree.TreeNode import TreeNode
from data_algo.algo.tree.build_tree import BuildTree
class BinaryTreeLevelTraverse:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if root is None:
return []
queue = [root]
res = []
while queue:
level = []
size = len(queue)
for i in range(size):
current = queue[0]
level.append(current.val)
queue.pop(0)
if current.left is not None:
queue.append(current.left)
if current.right is not None:
queue.append(current.right)
res.append(level)
return res
if __name__ == "__main__":
preorder = (1, 2, 5, 4, 6, 7, 3, 8, 9)
inorder = (5, 2, 6, 4, 7, 1, 8, 3, 9)
build = BuildTree()
tree = build.buildTree(preorder, inorder)
test = BinaryTreeLevelTraverse()
levelRes = test.levelOrder(tree)
print(levelRes)