自定义二叉搜索树

什么是二叉搜索树?

1.定义二叉搜索树类(最基本节点对象Node)

public class BinarySearchTree {
    class Node{
		int val;
		Node left;
		Node right;
		
		public Node(int val) {
			this.val = val;
		}
	}
	
	private Node root;
}

2.Insert方法(LeetCode701)

/**
* insert
* 1.判断根节点是否存在,不存在则创建新的根节点
* 2.根据二叉搜索树的性质(左节点<根节点<右节点)进行一种正确的插入方式
*/
public void insert(int val) {
		Node node = new Node(val);
		if(root==null) {
			root = node;
			return;
		}
		Node parent = root;
		while(true) {
			Node current = parent;
			if(val>current.val) {//右子树
				parent = parent.right;
				if(current.right==null) {
					current.right=node;
					return;
				}
			}else {//左子树
				parent = parent.left;
				if(current.left==null) {
					current.left=node;
					return;
				}	
			}
		}
	}

3.search方法(LeetCode700)

    /**
	  * 同样根据二叉搜索树的性质(左节点<根节点<右节点)
	  * @param val
	  * @return
	  */
	 public Node searchBST(int val) {
		 Node parent = root;
		 while(true) {
			 Node current = parent;
			 if(parent==null)return null;
			 if(val==parent.val) {
				 return current;
			 }else if(val<parent.val) {
				 parent = parent.left;
			 }else {
				 parent = parent.right;
			 }
		 }
	 }

4.delete方法(LeetCode450)

 public Node delete(int key) {
		 return helpDeleteNode(root,key);
	 }
	 
	 public int behNode(Node node) {
		 if(node.left==null)return node.val;
		 return behNode(node.left);		 
	 }
	 
	 public int preNode(Node node) {
		 if(node.right==null)return node.val;
		 return preNode(node.right);		 
	 }
	 /**
	  * 
	  * @param root
	  * @param key
	  * @return
	  */
	 public Node helpDeleteNode(Node root,int key) {
		 if(root==null)return null;
		 if(key<root.val) {
			 return helpDeleteNode(root.left,key);
		 }else if(key>root.val) {
			 return helpDeleteNode(root.right,key);
		 }else {
			 if(root.right==null&&root.left==null) {//删除的节点为叶节点,则直接置空
				 root = null;
			 }else if(root.right!=null) {//删除的节点具有右节点,找到右侧后继节点
				 root.val = behNode(root.right);
				 root.right = helpDeleteNode(root.right,root.val);
			 }else {//删除的节点没有右节点
				 root.val = preNode(root.left);
				 root.left = helpDeleteNode(root.left,root.val);
			 }
		 }
		 return root;
	 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值