- Binary Tree Level Order Traversal
中文English
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
Example
Example 1:
Input:{1,2,3}
Output:[[1],[2,3]]
Explanation:
level traversal
Example 2:
Input:{1,#,2,3}
Output:[[1],[2],[3]]
Explanation:
level traversal
Challenge
Challenge 1: Using only 1 queue to implement it.
Challenge 2: Use BFS algorithm to do it.
Notice
The first data is the root node, followed by the value of the left and right son nodes, and “#” indicates that there is no child node.
The number of nodes does not exceed 20.
这题跟传统的按层次遍历二叉树有点不一样是它要把每层的节点输入到一个vector里面去,这样的话要注意判断每层是不是已经到最后一个节点了。
解法1:用queue+NULL指针。先push root到quque里,再push一个NULL, 当pop出来的是root时,我们再把root的左右子节点push到queue中; 当pop出来的是NULL时,我们知道这一层已经结束了,我们把vector放到vv中,然后再push一个NULL节点。注意如果pop出来的是NULL, 我们再判断一下是不是整个queue都空了,如果是的话那么整个输出都结束,跳出循环。
注意:test case是NULL指针的情况和test case是1->2->3->4->5这种退化成链表的极端情形。
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int> > vv;
queue<TreeNode*> q;
q.push(root);
if (root)
q.push(NULL);
vector<int> v;
while(!q.empty()) {
TreeNode* t=q.front();
q.pop();
if (t) {
v.push_back(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
else{ //line end reached
if (v.size())
vv.push_back(v);
if (q.empty()) break;
v.clear();
q.push(NULL);
}
}
return vv;
}
int main()
{
#if 0 //test case 1
TreeNode t1(2);
TreeNode t2(9);
TreeNode t3(20);
TreeNode t4(15);
TreeNode t5(7);
t1.left=&t2;
t1.right=&t3;
t3.left=&t4;
t3.right=&t5;
vector<vector<int> > vv=levelOrder(&t1);
#endif
vector<vector<int> > vv=levelOrder(NULL); //test case 2
#if 0
TreeNode t1(1);
TreeNode t2(2);
TreeNode t3(3);
TreeNode t4(4);
TreeNode t5(5);
t1.left=&t2;
t2.left=&t3;
t3.left=&t4;
t4.left=&t5;
vector<vector<int> > vv=levelOrder(&t1);
#endif
//output
cout<<"["<<endl;
for (auto v : vv) {
cout<<" [ ";
for (auto i : v) {
cout<<i<<" ";
}
cout<<"]"<<endl;
}
cout<<"]"<<endl;
return 0;
}
复杂度为O(n),n为二叉树节点个数。
解法2:BFS分层遍历: queue+两层循环。
注意:
- Binary Search Tree的BFS不用加set或map来记录已经访问过的节点。因为二叉树的节点严格从上到下,层次分明,不会有已经访问过的节点又出现在queue的情况。
- 当q.pop()时把结果存入v中。这种写法比下面那种写法简便一些。
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int> > vv;
queue<TreeNode*> q;
if (root) q.push(root);
vector<int> v;
while(!q.empty()) {
int len=q.size();
while(len--) {
TreeNode* t=q.front();
q.pop();
v.push_back(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
vv.push_back(v);
v.clear();
}
return vv;
}
复杂度仍为O(n),n为二叉树节点个数。
下面这种写法也可以。
class Solution {
public:
/**
* @param root: A Tree
* @return: Level order a list of lists of integer
*/
vector<vector<int>> levelOrder(TreeNode * root) {
vector<vector<int>> result;
if (!root) return result;
queue<TreeNode *> q;
q.push(root);
result.push_back(vector<int>{root->val});
while(!q.empty()) {
int n = q.size();
vector<int> lines;
for (int i = 0; i < n; ++i) {
TreeNode * node = q.front();
q.pop();
if (node->left) {
q.push(node->left);
lines.push_back(node->left->val);
}
if (node->right) {
q.push(node->right);
lines.push_back(node->right->val);
}
}
if (lines.size() > 0) result.push_back(lines);
}
return result;
}
解法3:递归。Leetcode测试速度跟上面两个一样,并不慢。
代码如下:
void dfs(TreeNode* node, int depth, vector<vector<int> > &vv) {
if (!node) return;
if (depth==vv.size()) vv.resize(vv.size()+1); //let's say depth=1, vv.size()=1, it shows we need to add a new vector in vv
vv[depth].push_back(node->val);
dfs(node->left, depth+1, vv);
dfs(node->right, depth+1, vv);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int> > vv;
dfs(root, 0, vv);
return vv;
}
下面这个解法类似
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
getResult(root, 0, ans);
for (int i = 0, j = ans.size() - 1; i < j; i++, j--) {
swap(ans[i], ans[j]);
}
return ans;
}
private:
void getResult(TreeNode *root, int k, vector<vector<int>> &ans) {
if (root == NULL) return ;
if (k == ans.size()) ans.push_back(vector<int>());
ans[k].push_back(root->val);
getResult(root->left, k + 1, ans);
getResult(root->right, k + 1, ans);
return ;
}
};
解法4: 用两个queue,交替打印
代码如下:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A Tree
* @return: Level order a list of lists of integer
*/
vector<vector<int>> levelOrder(TreeNode * root) {
vector<vector<int>> result;
if (!root) return result;
queue<TreeNode *> q1, q2;
q1.push(root);
while(!q1.empty()) {
int n = q1.size();
vector<int> lines;
for (int i = 0; i < n; ++i) {
TreeNode * node = q1.front();
q1.pop();
lines.push_back(node->val);
if (node->left) {
q2.push(node->left);
}
if (node->right) {
q2.push(node->right);
}
}
result.push_back(lines);
swap(q1, q2);
}
return result;
}
};