102. 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,null,null,15,7]
,
3/9 20/15 7
Return its level order traversal as:
[3], [9,20], [15,7]]
Problem Solving Ideas:
Two queues are used for processing.
All nodes of this layer are processed with current queue currently, and this layer of information is recorded in the vector. Use next to record the next layer of node information.
After the current queue is processed, the vector of this layer of information is stored in the resulting vector. Empty the vector that stores this layer of information. Swap the current and next. The current queue is then re-processed.
The code is as follows:
/** * definition for a binary tree node. * struct treenode { * int val; * treenode * Left; * treenode *right; * treenode ( INT&NBSP;X) : val (x), left (null), right (null) {} * }; */class Solution {public: vector<vector<int>> levelorder (TreeNode* Root) { vector<vector<int>> result; queue<TreeNode *> current,next; vector<int> level; if (null == root) return result; current.push (Root); while (Current.size () > 0) { while (Current.size () > 0) { treenode *p = current.front (); current.pop (); level.push_back (P->val); if (P->left) &nbsP; next.push (P->left); if (p->right) Next.push (p->right); } result.push_back (level); level.clear (); current.swap (Next); } return result; }};
2016-08-05 17:21:32
This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1834819
leetCode102. Binary tree level Order traversal two fork trees hierarchy traversal