[LeetCode] Binary Tree Level Order Traversal
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 binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: queue<TreeNode*> q; //存放当前层的结点 vector<vector<int> >res;//存放最终的结果 vector<vector<int> > levelOrder(TreeNode *root) { if(root==NULL) return this->res; TreeNode *p = root; q.push(p); fun(); return res; } private: void fun() { if(this->q.empty()) return; TreeNode *pte; queue<TreeNode*> qnext;//存放下一层的结点 vector<int> te; while(!this->q.empty() ) { pte = this->q.front(); this->q.pop(); te.push_back(pte->val); if(pte->left!=NULL) { qnext.push(pte->left); } if(pte->right != NULL) { qnext.push(pte->right); } } res.push_back(te); this->q = qnext; fun(); } };
思路:用queue存放本层所有的结点,把本层处理完清空queue再存放下一层所有的结点。