Easy java solution without recursive


  • 0
    S
    public TreeNode deleteNode(TreeNode root, int key) {
    	if (root == null) return null;
    	TreeNode preNode = root;
    	TreeNode curNode = root;
    	while (curNode.val != key) {
    		preNode = curNode;
    		if (key > curNode.val) curNode = curNode.right;
    		else curNode = curNode.left;
    		if (curNode == null) return root;
    	}
    	update(curNode);
    	if (curNode.val < preNode.val) preNode.left = curNode.left;
    	else if (curNode.val > preNode.val) preNode.right = curNode.left;
    	else root = curNode.left;
    	return root;
    }
    
    private void update(TreeNode node) {
    	if (node.left != null){
    		TreeNode maxNode = node.left;
    		while (maxNode.right != null) maxNode = maxNode.right;
    		maxNode.right = node.right;
    	} else {
    		node.left = node.right;
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.