标签:层次遍历
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]
]
这道题是对给定的一棵二叉树,要求分层遍历,即从上到下、从左至右的顺序访问每个结点并保存。这道题的一个注意点在于,不同层的结点保存在不同的vector容器中。所以,设立两个变量分别保存当前层结点个数curCount和下一层结点的个数nextCount。遍历当前层结点时,每访问一个结点,curCount减一,同时计算当前结点的左右孩子个数n,并nextCount+=n。当curCount减为0时表示当前层已经遍历结束,并将nextCount的值赋给curCount,nextCount清零。重复上述操作,直至队列为空。
下面贴上代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > ans;
queue<TreeNode*> q;
if (root == NULL)
return ans;
q.push(root);
int nextCount = 0;
int curCount = 1;
vector<int> temp;
while(!q.empty()){
TreeNode* p = q.front();
q.pop();
temp.push_back(p->val);
if (p->left){
q.push(p->left);
nextCount++;
}
if (p->right){
q.push(p->right);
nextCount++;
}
curCount--;
if (!curCount){
ans.push_back(temp);
temp=vector<int>();
curCount = nextCount;
nextCount = 0;
}
}
return ans;
}
};
[LeetCode]Binary Tree Level Order Traversal
标签:层次遍历
原文地址:http://blog.csdn.net/kaitankedemao/article/details/43796461