0%

二叉树的层次遍历

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

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

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

返回其层次遍历结果:

1
2
3
4
5
[
[3],
[9,20],
[15,7]
]

递归实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> collection;
levelOrderRecur(root, &collection, 0);
return collection;
}

void levelOrderRecur(TreeNode* root, vector<vector<int>>* collection, int deepth) {
if (!root) {
return;
}
if (collection->size() < deepth + 1) {
collection->resize(deepth + 1);
}
collection->at(deepth).push_back(root->val);
levelOrderRecur(root->left, collection, deepth + 1);
levelOrderRecur(root->right, collection, deepth + 1);
}