中等 二叉树的层次遍历
33%
通过
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
您在真实的面试中是否遇到过这个题?
Yes
样例
给出一棵二叉树 {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
返回它的层次遍历为:
[
[3],
[9,20],
[15,7]
]
挑战
只使用一个队列去实现它
只用了一个队列,用到了两个计数器,一个记录这一层完全二叉树应该有的节点,另一个记录这一层缺失的节点
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public:
vector<vector<int>> levelOrder(TreeNode *root) {
// write your code here
vector<vector<int>> res;
if(root == nullptr) {
return res;
}
vector<int> temp;
queue<TreeNode*> q;
q.push(root);
int i = 1;// points every level
int j = 0;// lost point every level
while(!q.empty()) {
TreeNode *p = q.front();
q.pop();
if (p==nullptr) {
++j;
}
else {
temp.push_back(p->val);
q.push(p->left);
q.push(p->right);
}
if (i == (temp.size() + j) && temp.size()!=0) {
res.push_back(temp);
temp.clear();
i*=2;
j*=2;
}
}
return res;
}
};