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

Binary Tree Level Order Traversal II--LeetCode

时间:2015-04-05 11:58:39      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   算法   

 

题目:

Given a binary tree, return the bottom-up level order traversal of its nodes‘ values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   /   9  20
    /     15   7

return its bottom-up level order traversal as:

[
  [15,7]
  [9,20],
  [3],
]

思路:和上面的一样,只不过需要注意到最后再输出

void LevelOrder(BinTree* root)
{
	if(root == NULL)
		return ;
	deque<BinTree*> de;
	int num;
	int curnum=0;
	int i,j;
	BinTree* node;
	de.push_back(root);
	vector<int> vec;
	vector<vector<int> > result;
	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;
			result.push_back(vec);
			vec.clear();
		}
	}
	for(i=result.size()-1;i>=0;i--)
	{
		for(j=0;j<result[i].size();j++)
			cout<<result[i][j]<<" ";
		cout<<endl;
		
	}
} 











Binary Tree Level Order Traversal II--LeetCode

标签:c++   leetcode   算法   

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

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