记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。
1、问题描述:
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
2、数据结构:
二叉树、栈
3、题解:
如图:设置两个栈,分别存放从左到右和从右到左的打印元素。每个循环,若stack1不为空,则每次取出最后一个节点,并且把取出节点的左、右节点依次放到stack2中;若stack2不为空,则每次取出最后一个节点,并且把取出节点的右、左节点依次放到stack2中。因为栈是先入后出,所以,stack1从左到右,stack2从右到左。
# -*- 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 []
stack1 ,stack2 = [pRoot],[]
res = []
while stack1 or stack2:
if stack1:
ptemp = []
while stack1:
temp_res = stack1.pop()
ptemp.append(temp_res.val)
if temp_res.left:
stack2.append(temp_res.left)
if temp_res.right:
stack2.append(temp_res.right)
res.append(ptemp)
if stack2:
ptemp = []
while stack2:
temp_res = stack2.pop()
ptemp.append(temp_res.val)
if temp_res.right:
stack1.append(temp_res.right)
if temp_res.left:
stack1.append(temp_res.left)
res.append(ptemp)
return res
4、复杂度分析:
时间复杂度:O(N)
空间复杂度:O(N)