LeetCode: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] ]
递归版
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 vector<vector<int>> levelOrder(TreeNode* root) { 13 vector<vector<int>> result; 14 traversal(root,1,result); 15 return result; 16 17 18 } 19 //先序遍历 按层压入结果 20 void traversal(TreeNode *node,int level,vector<vector<int>> &result) 21 { 22 if(node==NULL) return; 23 24 if(level>result.size()) 25 result.push_back(vector<int>()); 26 result[level-1].push_back(node->val); 27 traversal(node->left,level+1,result); 28 traversal(node->right,level+1,result); 29 30 } 31 };
两个队列实现 按层遍历记录结果
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 vector<vector<int>> levelOrder(TreeNode* root) { 13 14 queue<TreeNode *> node_queue1; 15 16 if(root!=NULL) node_queue1.push(root); 17 18 vector<vector<int>> result; 19 20 if(root==NULL) return result; 21 22 vector<int> val; 23 24 do{ 25 queue<TreeNode *> node_queue2; 26 27 while(!node_queue1.empty()) 28 { 29 TreeNode *node=node_queue1.front(); 30 node_queue1.pop(); 31 val.push_back(node->val); 32 if(node->left!=NULL) node_queue2.push(node->left); 33 if(node->right!=NULL) node_queue2.push(node->right); 34 } 35 result.push_back(val); 36 val.clear(); 37 node_queue1=node_queue2; 38 }while(!node_queue1.empty()); 39 40 return result; 41 42 } 43 };