#include <iostream>
#include <ctime>
#include <string>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;
/* the data structure of TreeNode */
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) {
// use two STL queue to travel the tree
queue<TreeNode *> q,temp;
vector<vector<int>> s;
TreeNode * front_val;
if(!root) {
return s;
}
q.push(root);
while(!q.empty()) {
//store each level nodes in v
vector<int> v;
while(!q.empty()) {
front_val = q.front();
q.pop();
if(front_val->left) {
temp.push(front_val->left);
}
if(front_val->right) {
temp.push(front_val->right);
}
v.push_back(front_val->val);
}
//put each v in s
s.push_back(v);
while(!temp.empty()) {
front_val = temp.front();
temp.pop();
q.push(front_val);
}
}
return s;
}
};
int main()
{
Solution s;
TreeNode * root = new TreeNode(3) ;
TreeNode * two = new TreeNode(9) ;
TreeNode * three = new TreeNode(20) ;
TreeNode * four = new TreeNode(15) ;
TreeNode * five = new TreeNode(7) ;
root->left = two;
root->right = three;
three->left = four;
three->right = five;
vector<vector<int>> v;
v = s.levelOrder(root);
return 0;
}
[leetcode] Binary Tree Level Order Traversal
最新推荐文章于 2021-11-17 20:57:12 发布