提交 67d3c911 编写于 作者: 梦境迷离's avatar 梦境迷离

add scala leetcode 669 *

上级 87a1c0be
......@@ -34,6 +34,7 @@ Leetcode Scala 实现
* [二叉树的坡度](./src/main/scala/io/github/dreamylost/Leetcode_563.scala)
* [根据二叉树创建字符串](./src/main/scala/io/github/dreamylost/Leetcode_606.scala)
* [两数之和 IV - 输入 BST](./src/main/scala/io/github/dreamylost/Leetcode_653.scala)
* [修剪二叉搜索树](./src/main/scala/io/github/dreamylost/Leetcode_669.scala)
## 链表
......
......@@ -114,4 +114,18 @@ object BTT extends App {
list
}
//根据中序的有序数组构造二叉树
def buildSearchTree(values: Seq[Int], l: Int, r: Int): TreeNode = {
if (l > r) {
return null
}
if (l == r) {
new TreeNode(values(l))
}
val mid = l + (r - l) / 2
val root = new TreeNode(values(mid))
root.left = buildSearchTree(values, l, mid - 1)
root.right = buildSearchTree(values, mid + 1, r)
root
}
}
package io.github.dreamylost
/**
* 669. 修剪二叉搜索树
*
* 给定一个二叉搜索树,同时给定最小边界L 和最大边界 R。通过修剪二叉搜索树,使得所有节点的值在[L, R]中 (R>=L) 。
* 你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根节点。
*
* @author 梦境迷离 dreamylost
* @since 2020-06-16
* @version v1.0
*/
object Leetcode_669 extends App {
val ret = trimBST(TreeNodeData.treeData3_5(), 1, 2)
println(ret)
/**
* 修剪BST树,其步骤为:
* 若为空树,返回NULL;
* 否则:
* 1.先修剪根,若根的值不在[L,R]范围内,则执行如下循环:
* 若根小于下限L,必然有其左子树结点全部小于L,放弃根和左子树,使右子树的根成为新树的根。
* 大于上限R的情况同理。最后结束时,要么根为空,要么根的值在[L,R]中。
* 2.递归修剪左子树。
* 3.递归修建右子树。
*
* @param root
* @param L
* @param R
* @return
*/
def trimBST(root: TreeNode, L: Int, R: Int): TreeNode = {
if (root == null) return null
if (root.value < L) {
return trimBST(root.right, L, R)
}
if (root.value > R) {
return trimBST(root.left, L, R)
}
root.left = trimBST(root.left, L, R)
root.right = trimBST(root.right, L, R)
root
}
}
......@@ -8,6 +8,12 @@ public class TreeNode {
public int value = 0;
public TreeNode left = null;
@Override
public String toString() {
return "TreeNode{" + "value=" + value + ", left=" + left + ", right=" + right + '}';
}
public TreeNode right = null;
public TreeNode(int val) {
......
......@@ -59,6 +59,16 @@ object TreeNodeData {
root
}
//搜索树
def treeData3_5(): TreeNode = {
val root = new TreeNode(1)
val r1 = new TreeNode(2)
val l1 = new TreeNode(0)
root.right = r1
root.left = l1
root
}
def treeData5_1(): TreeNode = {
val n1 = new TreeNode(1)
val n2 = new TreeNode(2)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册