题解 | #实现二叉树先序,中序和后序遍历#

实现二叉树先序,中序和后序遍历

https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

package main

import . "nc_tools"

func threeOrders(root *TreeNode) [][]int {
	// write code here
	res := make([][]int, 3)
	for i := 0; i < 3; i++ {
		res[i] = make([]int, 1010)
	}
	len := preOrder(root, res[0], 0)
	res[0] = res[0][0:len]
	len = midOrder(root, res[1], 0)
	res[1] = res[1][0:len]
	len = postOrder(root, res[2], 0)
	res[2] = res[2][0:len]
	return res
}

func postOrder(root *TreeNode, data []int, len int) int {
	if root == nil {
		return len
	}
	len = postOrder(root.Left, data, len)
	len = postOrder(root.Right, data, len)
	data[len] = root.Val
	len++
	return len
}

func midOrder(root *TreeNode, data []int, len int) int {
	if root == nil {
		return len
	}
	len = midOrder(root.Left, data, len)
	data[len] = root.Val
	len++
	len = midOrder(root.Right, data, len)
	return len
}

func preOrder(root *TreeNode, data []int, len int) int {
	if root == nil {
		return len
	}
	data[len] = root.Val
	len++
	len = preOrder(root.Left, data, len)
	len = preOrder(root.Right, data, len)
	return len
}

全部评论

相关推荐

去B座二楼砸水泥地:不过也可以理解,这种应该没参加过秋招
点赞 评论 收藏
分享
躺尸修仙中:因为很多92的也去卷中小厂,反正投递简历不要钱,面试不要钱,时间冲突就推,不冲突就面试积累经验
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务