[LeetCode102] 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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
分类:Tree BFS
代码:
递归:
1 class Solution { 2 private: 3 //递归 4 vector<vector<int>> res; 5 void dfs(TreeNode* root, int height) 6 { 7 if(!root) 8 return; 9 while(res.size() <= height) 10 res.push_back(vector<int>()); 11 res[height].push_back(root->val); 12 dfs(root->left,height+1); 13 dfs(root->right,height+1); 14 } 15 public: 16 vector<vector<int>> levelOrder(TreeNode* root) { 17 //递归 18 dfs(root,0); 19 return res; 20 } 21 };
非递归:
1 vector<vector<int>> levelOrder(TreeNode* root) { 2 vector<vector<int>> ans; 3 vector<int> temp; 4 if(!root) 5 return ans; 6 queue<TreeNode*> que; 7 que.push(root); 8 int parentSize = 1, childSize = 0; 9 while(!que.empty()) 10 { 11 auto node = que.front(); 12 que.pop(); 13 temp.push_back(node->val); 14 if(node->left) 15 { 16 ++childSize; 17 que.push(node->left); 18 } 19 if(node->right) 20 { 21 ++childSize; 22 que.push(node->right); 23 } 24 --parentSize; 25 if(parentSize == 0) 26 { 27 ans.push_back(temp); 28 temp.clear(); 29 parentSize = childSize; 30 childSize = 0; 31 } 32 } 33 return ans; 34 }