题解 | #重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

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

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param pre int整型一维数组 
 * @param vin int整型一维数组 
 * @return TreeNode类
*/
func reConstructBinaryTree( pre []int ,  vin []int ) *TreeNode {
    // write code here
    if length := len(pre); length == 0 {
        return nil
    }
    i := 0
    for i = 0; i  < len(vin); i++ {
        if vin[i] == pre[0] {
            break
        }
    }
    root := &TreeNode{pre[0], nil, nil}
    root.Left = reConstructBinaryTree(pre[1:i+1], vin[:i])
    root.Right = reConstructBinaryTree(pre[i+1:], vin[i+1:])
    return root
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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