Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1402 from wzqwtt/tree11
Browse files Browse the repository at this point in the history
添加(0106.从中序与后序遍历序列构造二叉树.md) Scala版本
  • Loading branch information
youngyangyang04 authored Jun 27, 2022
2 parents 5cdd184 + 0fe499a commit 5d92348
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions problems/0106.从中序与后序遍历序列构造二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
```

-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 comments on commit 5d92348

Please sign in to comment.