标签:
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] ]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
Tree Breadth-first Search
#include<iostream>
#include<vector>
#include<list>
#include <stack>
using namespace std;
//Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/*采用广度优先搜索的方法,一层一层的去搜索,搜索时用到了队列,将每一层的结点进队列,然后将每一层
的一次输出,而在题目要求中反过来显示,所以又增加了一个堆栈,来为后面反过来显示节点数据*/
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > last_result;//最终的结果
stack<vector<int> > stack_result;//作为中间结果
if(root==NULL)
return last_result;
list<TreeNode*> temp;//做计算的队列
TreeNode* temp_node;//作为中间变量
//int depth=1;
int row_size=1;//记录每一层的结点个数
temp.push_back(root);
while(!temp.empty())
{
vector<int> temp_result;//设置一个装每一层结点的中间vector
while(row_size--)
{
temp_node=temp.front();
temp.pop_front();
temp_result.push_back(temp_node->val);
if(temp_node->left!=NULL)//将左子树进队列
temp.push_back(temp_node->left);
if(temp_node->right!=NULL)//将右子树进队列
temp.push_back(temp_node->right);
}
row_size=temp.size();
stack_result.push(temp_result);//将每一层的数据压栈
}
while(!stack_result.empty())//最后按栈中的元素再反向的输出
{
last_result.push_back(stack_result.top());
stack_result.pop();
}
return last_result;
}
int main()
{
}
leetcode_107题——Binary Tree Level Order Traversal II (二叉树,广度优先搜索,队列,栈)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4431455.html