1. 程式人生 > >演算法-二叉查詢樹-刪除節點

演算法-二叉查詢樹-刪除節點

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


public class Solution {
    /*
     * @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.
     */
    public TreeNode removeNode(TreeNode root, int value) {
        // write your code here
    if(root == null)
    return root;
    if(value > root.val)
    root.right = removeNode(root.right,value);
    else if(value < root.val)
    root.left = removeNode(root.left,value);
    else if(root.left != null && root.right != null) //上述情況
    {
        root.val = findMin(root.right).val;
        root.right = removeNode(root.right,root.val);
    }
    else
    root = (root.left != null) ? root.left :root.right;//  三種情況:左子樹非空,右子樹空;左子樹空,右子樹非空;左子樹空,右子樹空。
    return root;
    }
    public TreeNode findMin(TreeNode t){
        if(t == null)
        return t;
        else if(t.left == null)
        return t;
        return findMin(t.left);
    }
}