如果输入的字符串是有效或无效的BST(二进制搜索树),我必须返回true或false。
问题是我用这种“模式”输入了一个非典型字符串:(ROOT(LEFT,RIGHT));每个元素之间都有一个空间,ROOT是中心节点,LEFT是左侧节点,RIGHT是右侧节点。如果节点为null,则编码为“-”,则叶子用数字值编码,如果节点具有某些子级,则以这种方式编码:例如B有两个子级(D在左侧,E在右侧),所以( A(B(D,E),C))
我试图将字符串拆分为String数组,但我不知道如何填充树,同时检查它是否是BST。如何按顺序填充树,但不能像字符串一样用这个输入字符串说?
我会尝试使用这种算法:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
//Java implementation to check if given Binary tree
//is a BST or not
/* Class containing left and right child of current
node and key value*/
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
public class BinaryTree {
// Root of the Binary Tree
Node root;
/*
* can give min and max value according to your code or can write a
function to
* find min and max value of tree.
*/
/*
* returns true if given search tree is binary search tree (efficient
version)
*/
boolean isBST() {
return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
/*
* Returns true if the given tree is a BST and its values are >= min and <= max.
*/
boolean isBSTUtil(Node node, int min, int max) {
/* an empty tree is BST */
if (node == null)
return true;
/* false if this node violates the min/max constraints */
if (node.data < min || node.data > max)
return false;
/*
* otherwise check the subtrees recursively tightening the min/max
constraints
*/
// Allow only distinct values
return (isBSTUtil(node.left, min, node.data - 1) &&
isBSTUtil(node.right, node.data + 1, max));
}
public static Node insert(Node root, int key)
{
// if the root is null, create a new node an return it
if (root == null) {
return new Node(key);
}
// if given key is less than the root node,
// recur for left subtree
if (key < root.data) {
root.left = insert(root.left, key);
}
// else recur for right subtree
else {
// key >= root.data
root.right = insert(root.right, key);
}
return root;
}
/* Driver program to test above functions */
public static void main(String args[]) throws
FileNotFoundException,IOException
{
BufferedReader b = new BufferedReader(new
FileReader("Input1Es2.txt"));
String[] treesStrings = b.readLine().replaceAll("[^0-9-,
()]","").split(",|(?<=\\()|(?=\\()|(?<=\\))|(?=\\))");
BinaryTree tree = new BinaryTree();
tree.root = new Node(4);
tree.root.left = new Node(3);
tree.root.right = new Node(5);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(3);
if (tree.isBST())
System.out.println("IS BST");
else
System.out.println("Not a BST");
}
}
我尝试手动插入并且可以正常工作,但是我不知道如何自动插入节点并同时检查有效性。
输入1:(100(19(17(2(7,7),3),36(25,1)))
输出1:不是BST
输入2:(8(3(1,6(4,7)),10(-,14(13,-))))
输出2:是BST