diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 188ad3cb..37a702b7 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -1091,7 +1091,53 @@ class Solution_0106 { } ``` +## Scala +106 从中序与后序遍历序列构造二叉树 + +```scala +object Solution { + def buildTree(inorder: Array[Int], postorder: Array[Int]): TreeNode = { + // 1、如果长度为0,则直接返回null + var len = inorder.size + if (len == 0) return null + // 2、后序数组的最后一个元素是当前根元素 + var rootValue = postorder(len - 1) + var root: TreeNode = new TreeNode(rootValue, null, null) + if (len == 1) return root // 如果数组只有一个节点,就直接返回 + // 3、在中序数组中找到切割点的索引 + var delimiterIndex: Int = inorder.indexOf(rootValue) + // 4、切分数组往下迭代 + root.left = buildTree(inorder.slice(0, delimiterIndex), postorder.slice(0, delimiterIndex)) + root.right = buildTree(inorder.slice(delimiterIndex + 1, len), postorder.slice(delimiterIndex, len - 1)) + root // 返回root,return关键字可以省略 + } +} +``` + +105 从前序与中序遍历序列构造二叉树 + +```scala +object Solution { + def buildTree(preorder: Array[Int], inorder: Array[Int]): TreeNode = { + // 1、如果长度为0,直接返回空 + var len = inorder.size + if (len == 0) return null + // 2、前序数组的第一个元素是当前子树根节点 + var rootValue = preorder(0) + var root = new TreeNode(rootValue, null, null) + if (len == 1) return root // 如果数组元素只有一个,那么返回根节点 + // 3、在中序数组中,找到切割点 + var delimiterIndex = inorder.indexOf(rootValue) + + // 4、切分数组往下迭代 + root.left = buildTree(preorder.slice(1, delimiterIndex + 1), inorder.slice(0, delimiterIndex)) + root.right = buildTree(preorder.slice(delimiterIndex + 1, preorder.size), inorder.slice(delimiterIndex + 1, len)) + + root + } +} +``` -----------------------