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 / 7
Return its level order traversal as:
[ 3], [9,20], [15,7]]
Ideas:
These two topics are very basic, BFS search.
Exercises
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: Vector<vector<int> > Levelorder (TreeNode *root) {Vector<vector<int> >Res; Vector<int>tmp; Queue<treenode *>Q; intCount =0, num =1; if(root==NULL)returnRes; Q.push (root); while(!Q.empty ()) { for(intI=0; i<num;i++) {root=Q.front (); Q.pop (); Tmp.push_back (Root-val); if(root->Left ) {Count++; Q.push (Root-Left ); } if(root->Right ) {Count++; Q.push (Root-Right ); }} res.push_back (TMP); Num=count; Count=0; Tmp.clear (); } returnRes; }};
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]]
Exercises
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: Vector<vector<int> > Levelorderbottom (TreeNode *root) {Vector<vector<int> >Res; Vector<int>tmp; Queue<treenode *>Q; intCount =0, num =1; if(root==NULL)returnRes; Q.push (root); while(!Q.empty ()) { for(intI=0; i<num;i++) {root=Q.front (); Q.pop (); Tmp.push_back (Root-val); if(root->Left ) {Count++; Q.push (Root-Left ); } if(root->Right ) {Count++; Q.push (Root-Right ); }} res.push_back (TMP); Num=count; Count=0; Tmp.clear (); } reverse (Res.begin (), Res.end ()); returnRes; }};
Binary Tree level Order traversal I II