层次遍历,把每一层结点的数存在一个vector里面。bfs,用两个队列,一个队列存结点,一个队列存层数。
看到网上的一些题解,还可以用dfs做,NB。
/**
* Definition for binary tree
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int> > ans;
vector<int> v;
if(root == NULL) return ans;
queue<TreeNode*> node;
queue<int> index;
node.push(root);
index.push(1);
TreeNode *n;
int i;
int tag = 1;
while(!node.empty()){
n = node.front();
i = index.front();
node.pop();
index.pop();
if(n->left != NULL){
node.push(n->left);
index.push(i+1);
}
if(n->right != NULL){
node.push(n->right);
index.push(i+1);
}
if(tag != i){
tag = i;
ans.push_back(v);
v.clear();
}
v.push_back(n->val);
}
ans.push_back(v);
return ans;
}
};