java查找二叉树的代码
时间: 2024-05-03 08:20:42 浏览: 90
以下是Java语言实现查找二叉树的代码:
```
class Node {
int value;
Node left, right;
Node(int val) {
value = val;
left = right = null;
}
}
public class BinarySearchTree {
Node root;
public BinarySearchTree() {
root = null;
}
public void insert(int val) {
root = insertRec(root, val);
}
Node insertRec(Node root, int val) {
if (root == null) {
root = new Node(val);
return root;
}
if (val < root.value)
root.left = insertRec(root.left, val);
else if (val > root.value)
root.right = insertRec(root.right, val);
return root;
}
public boolean search(int val) {
return searchRec(root, val);
}
boolean searchRec(Node root, int val) {
if (root == null)
return false;
if (root.value == val)
return true;
if (val < root.value)
return searchRec(root.left, val);
return searchRec(root.right, val);
}
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
System.out.println(tree.search(70));
System.out.println(tree.search(90));
}
}
```
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)