Algorithm (remove a node from a binary search numbers)

Given a binary search tree root node and a root value key , delete the binary search tree key corresponding to a node, and ensure that the properties of the same binary search tree. Returns the binary search tree (likely to be updated) a reference to the root node. 

Generally, delete nodes can be divided into two steps: 

First, find the node you want to delete; 
if found, delete it.

Explanation: The time complexity of the algorithm requires O (h), h is the height of the tree.

 
 

Example:

 
 
= root [5,3,6,2,4, null, 7] 
Key 3 = 

    5 
   / \ 
  3 6 
 / \ \ 
2 4 7 

nodes need to be removed for a given value is 3, so we first find the node 3, then delete it. 

A correct answer is [5,4,6,2, null, null, 7 ], as shown below. 

    5 
   / \ 
  46 
 / \ 
27 

further correct answer is [5,2,6, null, 4, null , 7]. 

    5 
   / \ 
  26 
   \ \ 
    47
 
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func deleteNode(root *TreeNode, key int) *TreeNode {
    if (root == nil) {
        return nil
    }
    if (key < root.Val) {
        root.Left = deleteNode(root.Left, key)
        return root
    } else if (key > root.Val) {
        the root 
        space // new assignment is cleared. make the distribution space, is initialized;= DeleteNode .right (root.Right, Key )
         return the root 
    } the else {
         IF (root.Left == nil) {
             return the root. Right 
        } 
        IF (root.Right == nil) {
             return the root. Left 
        } 
        // new new and make a difference, to remember 
        // create objects make can only be created by make the Map chan Slice 
        // make can only be used to allocate and initialize the type of slice, map, chan data. You can assign any new type of data; 
        // return a pointer new allocation, i.e., type * Type. make reference to returns, i.e. the Type;
        // make function only for the map, slice and channel, and does not return a pointer to 
        Node: = new new (the TreeNode) 
        Node = FindMin (the root. Right) 
        the root .VAL = Node. Val 
        the root .right = deleteNode (root.Right, Node . Val) 
    } 
    return the root 
} 

FUNC FindMin (Node * the TreeNode) * the TreeNode {
     for {
         // golang not the while 
        IF node.Left == nil {
             BREAK 
        } 
        Node = Node. Left 
    } 
    return Node 
}

 

Guess you like

Origin www.cnblogs.com/cjjjj/p/12550356.html