Java, normal way.


  • -1
    N
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode deleteNode(TreeNode root, int key) {
            if(root == null) return root;
            if(key < root.val){
                root.left = deleteNode(root.left,key);
            }else if(key > root.val){
                root.right = deleteNode(root.right, key);
            }else{
                if(root.left == null && root.right == null){
                    root = null;
                }else if(root.left == null){
                    root = root.right;
                }else if(root.right == null){
                    root = root.left;
                }else{
                    TreeNode mostLeft = findMostLeftNode(root.right);
                    root.val = mostLeft.val;
                    mostLeft.val = key;
                    root.right = deleteNode(root.right,key);
                }
            }
            return root;
        }
        private TreeNode findMostLeftNode(TreeNode root){
            while(root.left!=null){
                root = root.left;
            }
            return root;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.