Remove Node in Binary Search Tree

本文介绍了一种Java实现二叉树节点删除的方法,包括四种情况:节点为叶子节点、只有一侧子节点、两侧都有子节点,以及如何在特定节点被删除后找到并替换它的值。

This is one of the pretty interesting technical interview questions I see, it is rather fundamental, you probably have seen similar from your text book. But you know what, in the real interview process, few people can actually implement the code correctly, around 10% graduates from top CS schools, let's put it that way.


The following is my java implementation:


 public TreeNode remove(TreeNode root, int target){
	    	if(root==null)
	    		return root;
	    	if(target<root.data)
	    		root.left = remove(root.left,target);
	    	else if(target>root.data)
	    		root.right = remove(root.right,target);
	    	//now we find this node, root.data = target, just need to delete this node
	    	else{
	    		// case 1, root is a leaf node
	    		if(root.left==null && root.right==null)
	    			root = null;
	    		// case 2, root has only left subtree
	    		else if(root.right==null)
	    			root = root.left;
	    		// case 3, root has only right subtree
	    		else if(root.left==null)
	    			root = root.right;
	    		// case 4 root has both left and right subtree
	    		else{
	    			//we can either find the largest value from left subtree or smallest from right subtree
	    			root.data = findSmallest(root.right);
	    			// delete that duplicate node from right sub tree
	    			remove(root.right,root.data);
	    		}
	    		
	    	}
	    	return root;
	    }
	    
	    public int findSmallest(TreeNode root){
	    	if(root==null) return 0;
	    	if(root.left==null)
	    		return root.data;
	    	else return findSmallest(root.left);
	    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值