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

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

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

package main
import . "nc_tools"
/*
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param root TreeNode类 the root of binary tree
 * @return int整型二维数组
*/
func threeOrders( root *TreeNode ) [][]int {
    // write code here
    return order(root)
}

func order(root *TreeNode) [][]int {
    if root == nil {
        return make([][]int, 3)
    }
    rst := make([][]int, 3)
    rst[0] = append(rst[0],root.Val)
    left := order(root.Left)
    rst[0] = append(rst[0], left[0]...)
    rst[1] = append(rst[1], left[1]...)
    rst[1] = append(rst[1], root.Val)
    right := order(root.Right)
    rst[0] = append(rst[0], right[0]...)
    rst[1] = append(rst[1], right[1]...)
    rst[2] = append(rst[2], left[2]...)
    rst[2] = append(rst[2], right[2]...)
    rst[2] = append(rst[2], root.Val)
    return rst
}

全部评论

相关推荐

点赞 评论 收藏
分享
03-12 14:52
已编辑
长沙学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务