general answer..


  • 0
    F
    /**
     * 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 null;
            else if (root.val > key) root.left = deleteNode(root.left, key);
            else if (root.val < key) root.right = deleteNode(root.right, key);
            else {
                if (root.left != null && root.right != null) {
                    
                    TreeNode maxNode = getMaxNode(root.left);
                    root.val = maxNode.val;
                    root.left = deleteNode(root.left, maxNode.val);
                } else {
                    if (root.left == null) return root.right;
                    else if (root.right == null) return root.left;
                    else return root;
                }
            }
    
            return root;
        }
        
        private TreeNode getMaxNode(TreeNode root) {
            if(root != null) {
                if (root.right == null) {
                    return root;
                }
                else return getMaxNode(root.right);
            }
            
            return root;
        }
    }
    

Log in to reply
 

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