按之字形顺序打印二叉树

题目

给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
数据范围:0≤n≤1500,树上每个节点的val满足 ∣val∣<=100
要求:空间复杂度:O(n),时间复杂度:O(n)

思路

和层次遍历一样,分层遍历,用队列存储节点,先进先出,但是要注意的是遇到偶数层,每层的结果要反转。

代码

python版本:

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pRoot TreeNode类 
# @return int整型二维数组
#
class Solution:
    def Print(self , pRoot: TreeNode) -> List[List[int]]:
        # write code here
        res = []
        if(pRoot==None):
            return res
        storage = [pRoot]
        count = 0
        while(len(storage)):
            count += 1
            level_res = []
            length = len(storage)
            for i in range(length):
                top_node = storage.pop()
                level_res.append(top_node.val)
                if(top_node.left != None):
                    storage.insert(0, top_node.left)
                if(top_node.right != None):
                    storage.insert(0, top_node.right)
            if(count %2==0):
                level_res.reverse()
            res.append(level_res)
        return res
                

c++版本:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
//         stack<TreeNode* > stk;
        queue<TreeNode* > qu;
        vector<vector<int>> res;
        if(!pRoot){
            return res;
        }
        int level = 0;
        qu.push(pRoot);
        while(!qu.empty()){
            level++;
            vector<int> level_res;
            int length = qu.size();
            for(int i=0; i<length; i++){
                TreeNode* tmp = qu.front();
                level_res.push_back(tmp->val);
                qu.pop();
                if(tmp->left){
                    qu.push(tmp->left);
                }
                if(tmp->right){
                    qu.push(tmp->right);
                }
            }
            if(level%2==0){
                reverse(level_res.begin(), level_res.end());
            }
            res.push_back(level_res);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超超爱AI

土豪请把你的零钱给我点

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值