这题算是树遍历的基础,写这篇博客主要是为了记录两种代码风格的层序遍历。
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 7return its level order traversal as:[ [3], [9,20], [15,7]]
题目链接:
风格一:
记录当前层与下一层的节点数,一个队列保存节点,避免多队列的拷贝。/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector> levelOrderBottom(TreeNode* root) { vector > res; if(!root) return res; vector vlevel; queue q; q.push(root); int level1=1,level2=0; while(!q.empty()){ TreeNode* front = q.front(); q.pop(); vlevel.push_back(front->val); if(front->left){ q.push(front->left); ++level2; } if(front->right){ q.push(front->right); ++level2; } if(--level1 == 0){ //one level is over res.push_back(vlevel); level1 = level2;//next level level2=0;//next next level start vlevel.clear(); } } reverse(res.begin(),res.end()); return res; }};
风格二:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector> levelOrder(TreeNode* root) { vector > ret; if(root == NULL) return ret; queue Q; Q.push(root); while(!Q.empty()) { queue Qtmp; vector Vtmp; while(!Q.empty()) { TreeNode *front = Q.front(); Q.pop(); Vtmp.push_back(front->val); if(front->left != NULL) Qtmp.push(front->left); if(front->right != NULL) Qtmp.push(front->right); } ret.push_back(Vtmp); Q = Qtmp; } return ret; }};