Binary Tree level Order traversal
Topic links
Title Requirements:
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]]
This problem using the width of the first search can be, the specific program (8MS) is as follows:
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<vector<int>> Levelorder (treenode*root) { -vector<vector<int>>Retvec; - if(!root) the returnRetvec; - -Retvec.push_back (vector<int>{root->val}); -Queue<treenode *>que; + Que.push (root); - while(true) + { Avector<int>Vec; atQueue<treenode *>Q; - while(!que.empty ()) - { -TreeNode *tree =Que.front (); - Que.pop (); - if(tree->Left ) in { -Vec.push_back ((Tree->left)val); toQ.push (tree->Left ); + } - if(tree->Right ) the { *Vec.push_back ((tree->right)val); $Q.push (tree->Right );Panax Notoginseng } - } the + if(!q.empty ()) A { theque =Q; + Retvec.push_back (VEC); - } $ Else $ Break; - } - the returnRetvec; - }Wuyi};
Binary Tree level Order traversal II
Topic links
Title Requirements:
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]]
The problem is basically the same as the above topic, we just need to retvec the result of the last question and then reverse it, that is to add the following line:
1 reverse (retvec.begin (), Retvec.end ());
Such a program as long as 8ms, but the bottom of the basic program is 64ms:
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<vector<int>> Levelorderbottom (treenode*root) { -vector<vector<int>>Retvec; - if(!root) the returnRetvec; - -Retvec.insert (Retvec.begin (), vector<int>{root->val}); -Queue<treenode *>que; + Que.push (root); - while(true) + { Avector<int>Vec; atQueue<treenode *>Q; - while(!que.empty ()) - { -TreeNode *tree =Que.front (); - Que.pop (); - if(tree->Left ) in { -Vec.push_back ((Tree->left)val); toQ.push (tree->Left ); + } - if(tree->Right ) the { *Vec.push_back ((tree->right)val); $Q.push (tree->Right );Panax Notoginseng } - } the + if(!q.empty ()) A { theque =Q; + Retvec.insert (Retvec.begin (), VEC); - } $ Else $ Break; - } - the returnRetvec; - }Wuyi};
View Code
Leetcode "tree": Binary tree Level order traversal && Binary Tree level order traversal II