Data structure and algorithm to delete the subtree of the node whose value is x

Delete the subtree of the node whose value is x

topic

It is known that the binary tree is stored in a binary linked list, and the algorithm is completed: for each node whose element value is x in the tree, delete the subtree rooted at it, and release the corresponding space.

idea

  • To delete the subtree rooted at element value x, as long as its left and right subtrees can be deleted, the root node with value x can be released, so it is advisable to use post-order traversal. [Pre/Middle/Sequential]
  • **Algorithm idea: **Deleting a node with a value of x means that the left (right) child pointer of its parent node should be empty, and it is easy to find the parent node of a node with hierarchical traversal. This question requires to delete the subtree of the node whose element value is × in the tree, so it is necessary to traverse the complete binary tree. 【BFS】

coding

/**
 * 删除当前结点
 *
 * @param root 根节点
 */
public void removeChildNodes(TreeNode root) {
    
    
    if (root != null) {
    
    
        removeChildNodes(root.left);
        removeChildNodes(root.right);
	//这里我假设val=-1就是无效结点,也就是被删除了
        root.val = -1;
    }
}

/**
 * 搜索结点值为x的元素
 *
 * @param root 根元素
 * @param x    要比对的值
 */
public void searchNodesAndDel(TreeNode root, int x) {
    
    
    if (root != null) {
    
    
        if (root.val == x) {
    
    
            removeChildNodes(root.left);
            //root.left = null;
            removeChildNodes(root.right);
            //root.right = null;
        }
        searchNodesAndDel(root.left, x);
        searchNodesAndDel(root.right, x);
    }
}

Guess you like

Origin blog.csdn.net/qq_45074341/article/details/126902602