【发布时间】:2020-02-18 03:38:08
【问题描述】:
我遇到了一些问题,问题如下:
Given a pre-constructed Binary Search Tree and an array, determine if the array will produce the same Binary Search Tree.
现在,这个问题会为你预先构建一个BST,然后它会运行下面的代码:
boolean valid = true;
for (int i = 0;valid && i < arr.length; i ++) {
valid &= tree.checkPattern(arr[i]);
}
//These two methods below are in a different class. For every element in the array,
//the checkPattern method will be called, initially passing in the root of the BST
public void checkPattern(int key) {
recursiveFunction(root, key);
}
public boolean recursiveFunction(TreeNode current, int key){
// Recursive function
}
目标是编写recursiveFunction(root, arr[i]),提示TreeNode 类包含一个visited 布尔值,您将使用它来帮助实现此算法。
我似乎不太明白如何解决这个问题...给定一个密钥,您是否应该检查它在主 BST 中的位置,如果已经访问过父级,则返回假的?
【问题讨论】:
-
我的老师使用(用于 BFS 算法)步长/权重 1/2D(取决于地图类型)数组。这个数组只是充满了整数值(为方便起见,默认填充
Integer.MAX_VALUE),这是到达那里的成本,代码将检查以这种方式或以前找到的方式遍历它是否更有效. -
@FailingCoder BFS(广度优先搜索)与搜索 BST(二进制搜索树)有什么关系?在 BST 中,您可以直接沿着树向下走到您要查找的节点,每层只踩一个节点。 BFS 和 DFS(深度优先搜索)是关于遍历树中的每个节点。
标签: java recursion search tree binary