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,#,#,15,7}
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Hide Tags
Have you met this question in a real interview?
Yes
No
#include<iostream> #include<vector> #include<list> using namespace std; //Definition for binary tree 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> > last_result;//最终的结果 if(root==NULL) return last_result; list<TreeNode*> temp;//做计算的队列 TreeNode* temp_node;//作为中间变量 //int depth=1; int row_size=1;//记录每一层的结点个数 temp.push_back(root); while(!temp.empty()) { vector<int> temp_result;//设置一个装每一层结点的中间vector while(row_size--) { temp_node=temp.front(); temp.pop_front(); temp_result.push_back(temp_node->val); if(temp_node->left!=NULL)//将左子树进队列 temp.push_back(temp_node->left); if(temp_node->right!=NULL)//将右子树进队列 temp.push_back(temp_node->right); } row_size=temp.size(); last_result.push_back(temp_result); } return last_result; } int main() { }
时间: 2024-10-15 11:19:25