LeetCode—剑指 Offer 32 - I、II、III. 从上到下打印二叉树

剑指 Offer 32. 从上到下打印二叉树

题目描述:
使用层序遍历,遍历二叉树的三种题目。
[I] 从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
[II] 从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
[III] 请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

考察重点:着重注意题目3,使用Golang中的list数据结构,作为队列进行层次遍历。
第一题

func levelOrder(root *TreeNode) []int {
    if root == nil{
        return []int{}
    }
	res := make([]int, 1)
	list := make([]*TreeNode, 1)
	list[0] = root
	nowList, nextList := 0, 1
	for {
		i := nowList
		nowList = nextList
		for ; i < nowList; i++ {
			res = append(res, list[i].Val)
			print(list[i].Val)
			if list[i].Left != nil {
				list = append(list, list[i].Left)
				nextList++
			}
			if list[i].Right != nil {
				list = append(list, list[i].Right)
				nextList++
			}
		}
		if nowList == nextList {
			return res[1:]
		}
	}
}

第二题

func levelOrder(root *TreeNode) [][]int {
    if root == nil{
        return [][]int{}
    }
	res := [][]int{}
	list := make([]*TreeNode, 1)
	list[0] = root
	nowList, nextList := 0, 1
	for {
		i := nowList
		nowList = nextList
        tRes := []int{}
		for ; i < nowList; i++ {
			tRes = append(tRes, list[i].Val)
			print(list[i].Val)
			if list[i].Left != nil {
				list = append(list, list[i].Left)
				nextList++
			}
			if list[i].Right != nil {
				list = append(list, list[i].Right)
				nextList++
			}
		}
        res = append(res, tRes)
		if nowList == nextList {
			return res
		}
	}
}

第三题

func levelOrder(root *TreeNode) [][]int {
	if root == nil {
		return [][]int{}
	}
	res := [][]int{}
	rList := list.New()
	rList.PushBack(root)
	mark := false
	for rList.Len() != 0 {
		tLen := rList.Len()
		tRes := []int{}
		tList := list.New()
		if mark {
			for ; tLen > 0; tLen-- {
				nowT := rList.Front().Value.(*TreeNode)
				tRes = append(tRes, nowT.Val)
				if nowT.Right != nil {
					tList.PushBack(nowT.Right)
				}
				if nowT.Left != nil {
					tList.PushBack(nowT.Left)
				}
				rList.Remove(rList.Front())
			}
			mark = false
		} else {
			for ; tLen > 0; tLen-- {
				nowT := rList.Front().Value.(*TreeNode)
				tRes = append(tRes, nowT.Val)
				if nowT.Left != nil {
					tList.PushBack(nowT.Left)
				}
				if nowT.Right != nil {
					tList.PushBack(nowT.Right)
				}
				rList.Remove(rList.Front())
			}
			mark = true
		}
		for tList.Len() != 0 {
			rList.PushBack(tList.Back().Value.(*TreeNode))
			tList.Remove(tList.Back())
		}
		res = append(res, tRes)
	}
	return res
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Ostrich5yw

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值