LintCode 87: Remove Node in Binary Search Tree (二叉树经典题!)

本文介绍了一种在二叉搜索树中移除指定值节点的算法,通过递归和预处理策略,讨论了当目标节点无子节点、有一个子节点或两个子节点时的处理方式,提供了两种实现思路:一种是寻找前驱节点,另一种是寻找后续节点。
  1. Remove Node in Binary Search Tree
    中文English
    Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You should keep the tree still a binary search tree after removal.

Example
Example 1

Input:
Tree = {5,3,6,2,4}
k = 3
Output: {5,2,6,#,4} or {5,4,6,2}
Explanation:
Given binary search tree:
5
/
3 6
/
2 4
Remove 3, you can either return:
5
/
2 6

4
or
5
/
4 6
/
2

Example 2

Input:
Tree = {5,3,6,2,4}
k = 4
Output: {5,3,6,2}
Explanation:
Given binary search tree:
5
/
3 6
/
2 4
Remove 4, you should return:
5
/
3 6
/
2

解法1:这个思路比较简洁。基于PreOrder和递归。
思路:
首先看root是否为空,若是返回root。
然后看root->val是不是已经是value,如果是,

  1. 若root无左子树,返回右子树。
  2. 若root无右子树返回左子树。
  3. 若root的左右子树都存在,找root左子树中的最大值节点,找到后将root的右子树嫁接到最大值节点的右节点即可。当然,也可以找root右子树中的最小值节点,找到后将root的左子树嫁接到最小值节点的左节点。

代码如下:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param root: The root of the binary search tree.
     * @param value: Remove the node with given value.
     * @return: The root of the binary search tree after removal.
     */
    TreeNode * removeNode(TreeNode * root, int value) {
        if (!root) return NULL;
   
        if (root->val == value) {
            if (!root->left) return root->right;
            if (!root->right) return root->left;
            
            //find the maximum node in left sub-tree
            TreeNode * node = root->left;
            while(node->right) {
                node = node->right;
            }
            node->right = root->right;
            return root->left;
        }
        
        if (root->val > value) {
            root->left = removeNode(root->left, value);    
        } else {
            root->right = removeNode(root->right, value);
        }
        
        return root;
    }
};

二刷:上面的解法就是说,如果当前节点就是要找到节点,那么找到当前节点的前驱节点,然后删掉当前节点,接上前驱节点。

class Solution {
public:
    /*
     * @param root: The root of the binary search tree.
     * @param value: Remove the node with given value.
     * @return: The root of the binary search tree after removal.
     */
    TreeNode * removeNode(TreeNode * root, int value) {
        if (!root) return nullptr;
        if (value < root->val) {
            root->left = removeNode(root->left, value);
        } else if (value > root->val) {
            root->right = removeNode(root->right, value);
        } else {
            if (!root->left || !root->right) {
                TreeNode *temp = (root->left) ? root->left : root->right;
                delete(root);
                return temp;
            } else {
                //find the predecessor
                TreeNode *predecessor = root->left;
                while(predecessor->right) predecessor = predecessor->right;
                
                root->val = predecessor->val;
                root->left = removeNode(root->left, predecessor->val);
            }
        }
        return root;
    }
};

解法2:跟解法1差不多,但是是找到当前节点的后续节点,然后删除当前节点,接上后续节点。

class Solution {
public:
    /*
     * @param root: The root of the binary search tree.
     * @param value: Remove the node with given value.
     * @return: The root of the binary search tree after removal.
     */
    TreeNode * removeNode(TreeNode * root, int value) {
        if (!root) return nullptr;
        if (value < root->val) {
            root->left = removeNode(root->left, value);
        } else if (value > root->val) {
            root->right = removeNode(root->right, value);
        } else {
            if (!root->left || !root->right) {
                TreeNode *temp = (root->left) ? root->left : root->right;
                delete(root);
                return temp;
            } else {
                //find the successor
                TreeNode *successor = root->right;
                while(successor->left) successor = successor->left;
                
                root->val = successor->val;
                root->right = removeNode(root->right, successor->val);
            }
        }
        return root;
    }
};
以下是一个简单的二叉树实现的Java代码,包含了输出所有直径及其路径长度的方法: ```java public class BinaryTree<T> { private Node<T> root; // 构造函数 public BinaryTree(Node<T> root) { this.root = root; } // 节点类 private static class Node<T> { private T data; private Node<T> left; private Node<T> right; public Node(T data) { this.data = data; this.left = null; this.right = null; } } // 输出所有直径及其路径长度 public static <T> void diameterAll(BinaryTree<T> bitree) { if (bitree.root == null) { System.out.println("Binary tree is empty."); return; } List<List<Node<T>>> paths = new ArrayList<>(); List<Integer> diameters = new ArrayList<>(); findPaths(bitree.root, paths, new ArrayList<>()); calculateDiameters(bitree.root, paths, diameters); for (int i = 0; i < diameters.size(); i++) { System.out.println("Diameter: " + diameters.get(i) + ", Path: "); for (Node<T> node : paths.get(i)) { System.out.print(node.data + " "); } System.out.println(); } } // 查找所有路径 private static <T> void findPaths(Node<T> node, List<List<Node<T>>> paths, List<Node<T>> path) { if (node == null) { return; } path.add(node); if (node.left == null && node.right == null) { paths.add(new ArrayList<>(path)); } else { findPaths(node.left, paths, path); findPaths(node.right, paths, path); } path.remove(path.size() - 1); } // 计算直径 private static <T> int calculateDiameters(Node<T> node, List<List<Node<T>>> paths, List<Integer> diameters) { if (node == null) { return 0; } int leftHeight = calculateDiameters(node.left, paths, diameters); int rightHeight = calculateDiameters(node.right, paths, diameters); int diameter = leftHeight + rightHeight; diameters.add(diameter); return Math.max(leftHeight, rightHeight) + 1; } public static void main(String[] args) { // 创建二叉树示例 Node<Integer> node1 = new Node<>(1); Node<Integer> node2 = new Node<>(2); Node<Integer> node3 = new Node<>(3); Node<Integer> node4 = new Node<>(4); Node<Integer> node5 = new Node<>(5); node1.left = node2; node1.right = node3; node2.left = node4; node3.right = node5; BinaryTree<Integer> bitree = new BinaryTree<>(node1); // 输出所有直径及其路径长度 diameterAll(bitree); } } ``` 这段代码使用了二叉树的先序遍历来查找所有路径,然后计算每个路径的直径。最后,输出每个直径及其路径长度。以上是一个简单的实现,你可以根据自己的需求进行修改和扩展。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值