按之字形顺序打印二叉树

本文介绍了一种特殊的二叉树打印方式——之字形打印,并提供了两种实现方案。一种是通过层次遍历结合队列的方法,另一种是使用两个栈来提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

思路:利用层次遍历,但加入本层levelque和下一层nextlevel,加入righttoleft判断是否需要逆序,res存放最终值
1.根节点加入levelque中
2.while leveque:针对每层创建一个nextlevel(存入左子树和右子树),curvalue存放当前层的值
3.根据是否需要逆序,将curvalue是否逆序
4.然后将curvalue加入res中,nextlevel给level

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        levelque=[pRoot]
        righttoleft=False
        res=[]
        while levelque:
            curvalue=[]
            nextlevel=[]
            for i in levelque:
                curvalue.append(i.val)
                if  i.left:
                    nextlevel.append(i.left)
                if  i.right:
                    nextlevel.append(i.right)
            if righttoleft:
                curvalue.reverse()
            if curvalue:
                res.append(curvalue)
            levelque=nextlevel
            righttoleft= not righttoleft
        return res

reverse方法时间复杂度比较高

思路二:用两个stack,用空间换取时间效率

import java.util.ArrayList;
import java.util.Stack;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res=new ArrayList<>();
        if(pRoot==null) return res;
        Stack<TreeNode> s1=new Stack<>();
        Stack<TreeNode> s2=new Stack<>();
        s1.push(pRoot);
        int level=1;
        while(!s1.isEmpty()||!s2.isEmpty()){
            ArrayList<Integer> list=new ArrayList<>();
            if(level++%2!=0){//层级,奇数,偶数
                while(!s1.isEmpty()){
                    TreeNode cur=s1.pop();
                    list.add(cur.val);
                    if(cur.left!=null) s2.push(cur.left);//s2逆序,先进后厨
                    if(cur.right!=null) s2.push(cur.right);
                }
            }
            else{//逆序
                while(!s2.isEmpty()){
                    TreeNode cur=s2.pop();
                    list.add(cur.val);
                    if(cur.right!=null) s1.push(cur.right);
                    if(cur.left!=null) s1.push(cur.left);
                }
            }
            res.add(list);
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值