mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0106.从中序与后序遍历序列构造二叉树.md Scala版本
This commit is contained in:
@ -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>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user