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] ]
/** * 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) { queue<TreeNode*> nodes; vector< vector<int> > result; vector<int> tmp; if(NULL==root) return result; nodes.push(root); while(!nodes.empty()) {//读取的同时,把下一层压入队列当中 int length=nodes.size(); int i=0; while(i<length) { TreeNode* tmpNode=nodes.front(); tmp.push_back(tmpNode->val); if(tmpNode->left) nodes.push(tmpNode->left); if(tmpNode->right) nodes.push(tmpNode->right); nodes.pop(); i++; } result.push_back(tmp); tmp.clear(); } return result; } };
时间: 2024-11-06 16:28:52