描述
给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
该二叉树层序遍历的结果是
[
[3],
[9,20],
[15,7]
]
c++:
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > levelOrder(TreeNode* root) { // write code here queue< TreeNode* > Q; vector< vector<int> > res; vector<int> s; if (root==NULL) return res; Q.push(root); int num1=1,num2=0; while(!Q.empty()) { TreeNode* p=Q.front(); if (p->left!=NULL) {Q.push(p->left); num2++;} if (p->right!=NULL) {Q.push(p->right); num2++;} s.push_back(p->val); num1--; Q.pop(); if (num1==0) { res.push_back(s); s.clear(); num1=num2; num2=0; } } return res; } };