码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Level Order Traversal--LeetCode

时间:2015-04-05 12:00:39      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   算法   

题目:

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]
]

思路:使用队列,等到这一层遍历结束再输出

void LevelOrder(BinTree* root)
{
	if(root == NULL)
		return ;
	deque<BinTree*> de;
	int num;
	int curnum=0;
	int i;
	BinTree* node;
	de.push_back(root);
	vector<int> vec;
	num =1;
	while(!de.empty())
	{
		node = de.front();
		de.pop_front();
		num--;
		vec.push_back(node->value);
		if(node->left != NULL)
		{
			de.push_back(node->left);
			curnum++;
		}
		if(node->right !=NULL)
		{
			de.push_back(node->right);
			curnum++;
		}
		if(num ==0)
		{
			num =curnum;
			curnum =0;
			for(i=0;i<vec.size();i++)
			cout<<vec[i]<<" ";
			cout<<endl;
			vec.clear();
		}
	}
} 


Binary Tree Level Order Traversal--LeetCode

标签:c++   leetcode   算法   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/44886293

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!