美文网首页
打卡-从前序与中序遍历序列构造二叉树

打卡-从前序与中序遍历序列构造二叉树

作者: A邱凌 | 来源:发表于2020-05-23 17:24 被阅读0次

从前序与中序遍历序列构造二叉树(中等)

import Utils.TreeNode
import Utils.TreeNode.preOrderTraversalWithRecursive

class BuildTree {
    /*
    * 根据一棵树的前序遍历与中序遍历构造二叉树。
    * 注意:
    * 你可以假设树中没有重复的元素。
    * 例如,给出
    * 前序遍历 preorder = [3,9,10,20,15,7]
    * 中序遍历 inorder = [10,9,3,15,20,7]
    * 返回如下的二叉树:

    3
   / \
  9  20
 /   /  \
10   15   7

    * */
    fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
        if (preorder.size == 0) {
            return null
        }
        if (preorder.size == 1) {
            return TreeNode(preorder[0])
        }
        val rootNode = preorder[0]
        var rootIndex: Int = 0
        for ((index, value) in inorder.withIndex()) {
            if (rootNode == value) {
                //2
                rootIndex = index
            }
        }

        val treeNode = TreeNode(rootNode)
        treeNode.left = buildTree(preorder.sliceArray(1..rootIndex), inorder.sliceArray(0 until (rootIndex)))
        treeNode.right = buildTree(preorder.sliceArray(rootIndex + 1 until preorder.size), inorder.sliceArray(rootIndex + 1 until inorder.size))
        return treeNode
    }
}

fun main() {
    preOrderTraversalWithRecursive(BuildTree().buildTree(intArrayOf(3, 9,10, 20, 15, 7), intArrayOf(10,9, 3, 15, 20, 7)))
}


相关文章

网友评论

      本文标题:打卡-从前序与中序遍历序列构造二叉树

      本文链接:https://www.haomeiwen.com/subject/rrjlahtx.html