今天在剑指offer上刷了树的层次遍历
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
vector<int> PrintFromTopToBottom(TreeNode* root)
{
vector<int> res; //存放结果
queen<TreeNode*> q; //创建一个队列
TreeNode* temp;
if(root == NULL)
return res;
q.push(root); //root node into the queen
while(!q.empty()) //队列不为空不结束
{
temp = q.front(); //temp point to the first element of queen
res.push_back(temp->val); //res +=temp.val
if(temp->left!=NULL)
q.push(temp->left); //Tree node in turn into the quene
if(temp->right != NULL)
q.push(temp->right);
q.pop();
}
return res;
}
思路就是创建一个队列,首先根节点入队,然后根节点值存入vector中,然后遍历左节点和右节点,分别入队,然后pop 队列的第一个点,然后循环,最后队列为空结束。
下面是python版本
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
res = []
if not root:
return []
q = [root]
while len(q):
t = q.pop(0) //这里和C++不一样的是由于取队列的第一个值的方式不同,python这里是把第一个值吐出来,C++是
用.front()函数读这个数,最后在一次循环的最后pop出
res.append(t.val)
if t.left:
q.append(t.left)
if t.right:
q.append(t.right)
return res
还复习了一下队列的使用方式:
queue单向队列与栈有点类似,一个是在同一端存取数据,另一个是在一端存入数据,另一端取出数据。单向队列中的数据是先进先出(First In First Out,FIFO)。在STL中,单向队列也是以别的容器作为底部结构,再将接口改变,使之符合单向队列的特性就可以了。因此实现也是非常方便的。下面就给出单向队列的函数列表和VS2008中单向队列的源代码。单向队列一共6个常用函数(front()、back()、push()、pop()、empty()、size()),与栈的常用函数较为相似。
push 是在尾部增加数据
pop是默认在头部删除数据