Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
题意是进行二叉树的层次遍历。其实层次遍历就类似于广度优先搜索,非递归结构的话用队列就可以实现。而递归的话则会更加简单。所以下面给出递归和非递归的形式:
递归版本:
Code:(LeetCode运行3ms)
/**
* 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> > result;
levelOrder(root, 1, result);
return result;
}
void levelOrder(TreeNode *root, int level, vector<vector<int> > &result) {
if (!root) {
return;
}
if (result.size() < level) {
result.push_back(vector<int>());
}
result[level - 1].push_back(root -> val);
levelOrder(root -> left, level + 1, result);
levelOrder(root -> right, level + 1, result);
}
};
Code:(LeetCode运行3ms)
/**
* 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> > result;
queue<TreeNode *> currentLevelQueue, nextLevelQueue;
if (!root) {
return result;
} else {
currentLevelQueue.push(root);
}
while (!currentLevelQueue.empty()) {
vector<int> temp;
while (!currentLevelQueue.empty()) {
TreeNode *pointer = currentLevelQueue.front();
currentLevelQueue.pop();
temp.push_back(pointer -> val);
if (pointer -> left) {
nextLevelQueue.push(pointer -> left);
}
if (pointer -> right) {
nextLevelQueue.push(pointer -> right);
}
}
result.push_back(temp);
swap(currentLevelQueue, nextLevelQueue);
}
return result;
}
};
非递归比较难写一点,需要用一个queue来保存当前层次的结点,再用一个queue来保存下一层次的结点。因为题目要求的返回值是一个vector<vector<int> >类型,所以每一层的保存都是分开的。