编程之旅-Day28

目录

Day28-学习内容:

1.剑指Offer

面试题32:之字形打印二叉树

面试题32:把二叉树打印成多行

面试题37:序列化二叉树

 2.Leetcode

例1:通过前序和中序遍历构建二叉树

例2:判断二叉树是否对称

例3:判断两颗树是否相等

3.机器学习专项


1.剑指Offer

面试题32:之字形打印二叉树

题目描述:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

思路:使用两个栈层次遍历,奇数行和偶数行入栈顺序不同。

代码:

技巧:栈数组和变量的使用

stack<TreeNode*> levels[2];

 int current=0;

 int next=1;

class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > res;
        if(pRoot==nullptr) return res;
        stack<TreeNode*> levels[2];
        int current=0;
        int next=1;
        levels[current].push(pRoot);
        vector<int> temp;
        while(!levels[0].empty()||!levels[1].empty()){
            TreeNode* p=levels[current].top();
            levels[current].pop();
            temp.push_back(p->val);
            if(current==0){
                if(p->left){
                    levels[next].push(p->left);
                }
                if(p->right){
                    levels[next].push(p->right);
                }
            }
            else{
                if(p->right){
                    levels[next].push(p->right);
                }
                if(p->left){
                    levels[next].push(p->left);
                }
            }
            if(levels[current].empty()){
                current=1-current;
                next=1-next;
                res.push_back(temp);
                temp.clear();
            }
        }
        return res;
    }  
};

 

面试题32:把二叉树打印成多行

题目描述:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

思路:使用队列

代码:

class Solution {
public:
        vector<vector<int> > Print(TreeNode* pRoot) {
            vector<vector<int> > res;
            if(pRoot==nullptr) return res;
            queue<TreeNode*> q;
            q.push(pRoot);
            while(!q.empty()){
                int n=q.size();
                vector<int> temp;
                while(n--){
                    TreeNode* p=q.front();
                    temp.push_back(p->val);
                    q.pop();
                    if(p->left){
                        q.push(p->left);
                    }
                    if(p->right){
                        q.push(p->right);
                    }
                }
                res.push_back(temp);
            }
            return res;
        }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值