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 / 7
Return its level order traversal as:
[ 3], [9,20], [15,7]]
Problem-Solving ideas: You can use DFS and BFS thinking to solve the problem. Dfs simply iterates through the depth, outputting the values of the corresponding depths sequentially. When using the BFS layered traversal, the first memory is super, then added the depth information AC
#include <iostream> #include <vector> #include <queue> #include <map> #include <algorithm >using namespace std;struct TreeNode {int val; TreeNode *left; TreeNode *right; TreeNode (int x): Val (x), left (null), right (NULL) {}};//memory is too large vector<vector<int> > Levelorder (TreeNode *root ) {queue<treenode*> bfs_queue;vector<int> levelval;vector<treenode*> LevelNode;vector<vector <int> > result;if (root = NULL) return Result; Bfs_queue.push (root); while (! Bfs_queue.empty ()) {while (! Bfs_queue.empty ()) {treenode* Curnode = Bfs_queue.front (); Levelval.push_back (Curnode->val); Bfs_queue.pop (); if (curnode->left) levelnode.push_back (curnode->left); if (curnode->right) LevelNode.push_ Back (curnode->right);} Result.push_back (Levelval); For_each (Levelnode.begin (), Levelnode.end (), [&bfs_queue] (treenode* a) {BFS_ Queue.push (a); }); Levelval.clear ();} return Result;} Introduction of depth information:acvector<vector<int> > Levelorder (TreeNode *root) {queue<pair<treenode*,int> > Bfs_queue;vector<int> levelval;vector<vector<int> > Result;if (root = = NULL) return Result; Bfs_queue.push (Make_pair (root,0)); int curlevel = 0;while (! Bfs_queue.empty ()) {treenode* Curnode = Bfs_queue.front (). First;if (Bfs_queue.front (). Second! = Curlevel) {Result.push _back (Levelval); Levelval.clear (); Curlevel = Bfs_queue.front (). Second;} Levelval.push_back (Curnode->val); Bfs_queue.pop (); if (curnode->left) Bfs_queue.push (Make_pair (curnode->left, Curlevel + 1)); if (Curnode-> right) Bfs_queue.push (Make_pair (curnode->right, Curlevel + 1));} Result.push_back (levelval); return Result;}
Binary Tree level Order traversal