Delete Node in a BST

来源:互联网 发布:网络用语鸡汤什么意思 编辑:程序博客网 时间:2024/06/05 08:03

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

  1. Search for a node to remove.
  2. If the node is found, delete the node.

Note: Time complexity should be O(height of tree).

Example:

root = [5,3,6,2,4,null,7]key = 3    5   / \  3   6 / \   \2   4   7Given key to delete is 3. So we find the node with value 3 and delete it.One valid answer is [5,4,6,2,null,null,7], shown in the following BST.    5   / \  4   6 /     \2       7Another valid answer is [5,2,6,null,4,null,7].    5   / \  2   6   \   \    4   7

伪代码是懂得,具体实现还有一点不太明白。会把流程补充上来。自己实现的时候没有对deleteNOde这个方法的返回值有一个很明确的认识。它应该是这个意思:对于删除方法,它返回当前这棵树的根节点,而这课根节点可能已经被更新过了,也有可能没有更新过。

删除的时候会考虑到三种情况:

1 root.left == null

2. root..right == null

以上两种很容易实现

3. 都不为空,那么这里选择的用右子树的后继替换根节点。先找到后继的值,然后更新根节点的值;再root.right = deleteNode(root.right, root.val),这种方式可以将后继节点删除掉,虽然麻烦了点。在实现findAndDeleteSuccessor这个方法的时候,尝试把父节点也放进去,在这个方法里直接删除后继节点。但是会报错,不知道是为什么,测试用例到70的时候过不去。待更新。

代码:

public TreeNode deleteNode(TreeNode root, int key) {        //TreeNode ret = root;        if(root == null) return null;        if(root.val == key){            if(root.left == null){                root = root.right;            }else if(root.right == null){                root = root.left;            }else{                 //if all not null find 节点的后继               root.val = findAndDeleteSuccessor(root.right);               root.right = deleteNode(root.right, root.val);            }        }else if(root.val > key){             root.left = deleteNode(root.left, key);        }else{             root.right = deleteNode(root.right, key);        }        return root;    }    private int findAndDeleteSuccessor(TreeNode node){        while(node != null && node.left != null){            node = node.left;        }        TreeNode ret = node;        node = null;        return ret.val;    }


0 0
原创粉丝点击