二叉树打印练习题

有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。
给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。

用队列实现queue
用到队列queue的

queue <TreeNode> Q;
Q.front()//队列最先进去的元素
Q.back()//队列最后进去的元素
Q.push(x)//x元素进入队列
Q.pop()//弹出队列最先进去的元素
//二维vector的bush_back();
//为什么要申明中间变量node,直接用temp.front()不行呢?
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/

class TreePrinter {
public:
    vector<vector<int> > printTree(TreeNode* root) {
        vector<vector<int> > rec;
        if(root==NULL) 
            return rec;

        queue <TreeNode*> temp;
        //TreeNode *t=root;
        temp.push(root);
        TreeNode *last=root;
        TreeNode *nlast=NULL;
        TreeNode *node=NULL;
        vector<int> rec1;
        while(!temp.empty())
        {
            node=temp.front();
            if(node->left)
            {
                temp.push(node->left);
                nlast=temp.back();
            }
            if(node->right)
            {
                temp.push(node->right);
                nlast=temp.back();
            }
            rec1.push_back(node->val);
            if(node==last)
            {
                last=nlast;
                rec.push_back(rec1);
                rec1.clear();
            }
            temp.pop();
        }
        return rec;
        // write code here
    }
};

用双向队列deque

temp.push();
temp.pop_front();
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode *root) {
vector<int> res;
        deque<TreeNode*> temp;
        if(root==NULL) return res;
        TreeNode *cur=root;
        temp.push_back(cur);  //将头结点插入队列中
        while(!temp.empty()){
            if(temp.front()->left!=NULL) temp.push_back(temp.front()->left);  //对于遍历到的节点,将他的左右节点放入到队列末尾
            if(temp.front()->right!=NULL) temp.push_back(temp.front()->right);
            res.push_back(temp.front()->val); //打印改节点
            temp.pop_front();  //弹出该节点
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值