题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
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 }