剑指offer——从上到下打印二叉树(面试题32)

题目一:不分行从上到下打印二叉树

  • 题目描述:

从上到下按层打印二叉树,同一层结点从左至右输出。

  • 详细代码:
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        if not root:
        	return []
        res = []
        res_val = []
        res.append(root)
        while len(res) > 0:
        	node = res.pop(0)
        	res_val.append(node.val)
        	if node.left:
        		res.append(node.left)
        	if node.right:
        		res.append(node.right)
        return res_val	

题目二:分行从上到下打印二叉树

  • 题目描述:

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

  • 详细代码:
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def PrintFromTopToBottom(self, root):
        # write code here
        if not root:
        	return []
        res = []
        res_val = []
        res.append(root)
        NextLevel = 0
        toBePrinted = 1
        temp = []
        
        while len(res) > 0:
        	node = res[0]
        	temp.append(node.val)
        	if node.left:
        		res.append(node.left)
        		NextLevel += 1
        	if node.right:
        		res.append(node.right)
        		NextLevel += 1

			del res[0]
			toBePrinted -= 1
			if toBePrinted == 0:
				res_val.append(temp)
				toBePrinted = NextLevel
				NextLevel = 0
				temp = []
        return res_val	

题目三:之字形打印二叉树

  • 题目描述:

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

  • 详细代码:
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def PrintFromTopToBottom(self, root):
        # write code here
        if not root:
        	return []

		res = []
		nodes = [root]
		right = Ture

		while res:
			CurStack = []
			NextStack = []
			if right:
				for node in nodes:
					CurStack.append(node.val)
					if node.left:
						NextStack.append(node.left)
					if node,right:
						NextStack.append(node.right)
			else:
				for node in nodes:
					CurStack.append(node.val)
					if node,right:
						NextStack.append(node.right)
					if node.left:
						NextStack.append(node.left)
			res.append(CurStack)
			right = not right
			NextStack.reverse()
			nodes = NextStack
		return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值