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 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Solution: 1. Use queue. In order to seperate the levels, use 'NULL' as the end indicator of one level.
2. DFS.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int> > levelOrder(TreeNode *root) { 13 vector<vector<int> >res; 14 levelOrderRe(root, 0, res); 15 return res; 16 } 17 18 void levelOrderRe(TreeNode* root, int level, vector<vector<int> >& res) 19 { 20 if(!root) return; 21 if(res.size() <= level) { 22 res.push_back(vector<int>()); 23 } 24 res[level].push_back(root->val); 25 levelOrderRe(root->left, level+1, res); 26 levelOrderRe(root->right, level+1, res); 27 } 28 };