Binary Tree level Order traversalTitle Description: 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]
]
Problem-solving idea: to find each layer of a binary tree node, and stored in a two-tuple array by layer. The use of BFS can be achieved. My blog "Binary Tree Generation, traversal, as well as the shortest longest path query" has been mentioned in the use of the queue can achieve a two-yuan tree horizontal traversal, in this subject, we still use the queue to the tree BFs, using two queues, Q represents the Layer node, Q1 represents the lower node, in turn queue, out of the queue, Two-dimensional vectors can be constructed. The code is as follows:
Class Solution {public: vector<vector<int>> levelorder (treenode* root) { vector<vector< int>> Res; vector<int> temp; if (root==null) return res; queue<treenode*> Q; Q.push (root); TreeNode *node; while (!q.empty ()) { queue<treenode*> Q1; while (!q.empty ()) { node=q.front (); Temp.push_back (node->val); Q.pop (); if (node->left!=null) { q1.push (node->left); } if (node->right!=null) { q1.push (node->right); } } Res.push_back (temp); q=q1; Temp.clear (); } return res; }};
Binary Tree level Order traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes ' values. (ie, from the left-to-right, the level by level from the leaf to root).
For example:
Given binary Tree {3,9,20,#,#,15,7}
,
3 / 9 / 7
Return its bottom-up level order traversal as:
[ [15,7], [9,20], [3]]
Solution thinking: The same binary Tree level Order traversal, the last two-dollar vector flip, the code is as follows:
Class Solution {public: vector<vector<int>> levelorderbottom (treenode* root) { Vector<vector <int>> Res; vector<int> temp; if (root==null) return res; queue<treenode*> Q; Q.push (root); treenode* node; while (!q.empty ()) { queue<treenode*> Q1; while (!q.empty ()) { node=q.front (); Q.pop (); Temp.push_back (node->val); if (node->left!=null) Q1.push (node->left); if (node->right!=null) Q1.push (node->right); } Res.push_back (temp); Temp.clear (); q=q1; } Reverse (Res.begin (), Res.end ()); return res; }};
Binary tree Level order traversal, binary tree level order traversal II