二叉排序数又称二叉查找树。它或者是一颗空树,或者是由具有下列性质的二叉树:
1、如果左子树不空,那么左子树上所有的值均小于它的根节点的值;
2、如果右子树不空,那么右子树所有的节点的值均大于它的根节点的值
3、左、右字数也分别为二叉排序树。
由于二叉树具有有序的特点,因此在笔试或面试的过程中经常会出现二叉树相关的题目。下面给出了二叉排树的实现代码:
package test;
class Node{
public int data;
public Node left;
public Node right;
public Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
public class BinaryTree {
private Node root;
public BinaryTree(){
root=null;
}
//将data插入到排序的二叉树中
public void insert(int data){
Node newNode=new Node(data);
if(root==null)
root=newNode;
else{
Node current=root;
Node parent;
while(true){//寻找插入的位置
parent=current;
if(data