LeetCode102 Binary Tree Level Order Traversal

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

样例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Input:
Given binary tree [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
Output:
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

思路

求二叉树的层序遍历。

BFS:初始化一个队列,存放节点信息以及对应的深度。由于是宽搜,所以每到达新的一层,就把上一层的信息全push到vector里。

DFS:在前序遍历的时候,初始化好相应深度的vector,若以后又访问到该层,直接push到相应层的vector中。

代码

BFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (root == NULL) return ans;
queue<pair<TreeNode*, int>> que;
que.push(make_pair(root, 1));
vector<int> temp;
int pre = 1;
while (!que.empty()) {
pair<TreeNode*, int>& p = que.front();
que.pop();
if (p.second != pre) { // 新的一层
ans.push_back(temp);
temp.clear();
pre = p.second;
}
temp.push_back(p.first->val);
if (p.first->left != NULL) que.push(make_pair(p.first->left, p.second + 1));
if (p.first->right != NULL) que.push(make_pair(p.first->right, p.second + 1));
}
ans.push_back(temp);
return ans;
}
};

DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> vec;
void dfs(TreeNode* root, int dep) {
if (root == NULL) return ;
// 第一次到达dep层,初始化一个空的vector
if (vec.size() == dep) vec.push_back(vector<int>());
vec[dep].push_back(root->val);
dfs(root->left, dep + 1);
dfs(root->right, dep + 1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
dfs(root, 0);
return vec;
}
};
分享到 评论