[LeetCode]Binary Tree Level Order Traversal
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] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
BFS,广度优先搜索。递归实现。迭代版需要用到队列。
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 */ 10 class Solution { 11 public: 12 void bfs(TreeNode* root,int level,vector<vector<int>>& result) 13 { 14 if(!root) return; 15 if(level>result.size()) result.push_back(vector<int>()); 16 result[level-1].push_back(root->val); 17 bfs(root->left,level+1,result); 18 bfs(root->right,level+1,result); 19 } 20 vector<vector<int>> levelOrder(TreeNode* root) { 21 vector<vector<int>> result; 22 bfs(root,1,result); 23 return result; 24 } 25 };