Easy solution without Recursion


  • 0
    C
    public class Solution {
        public TreeNode deleteNode(TreeNode root, int key) {
            TreeNode pre = null, cur = root;
            while (cur != null){
                if (cur.val < key){
                    pre = cur;
                    cur = cur.right;
                } else if(cur.val > key) {
                    pre = cur;
                    cur = cur.left;
                } else{
                    break;
                }
            }
            
            if (cur != null){
                TreeNode replaceNode = null;
                if (cur.right == null){
                    replaceNode = cur.left;
                } else {
                    replaceNode = cur.right;
                    if (cur.left != null){
                        if (cur.right.left != null){
                            TreeNode left = cur.left;
                            while (left.right != null){
                                left = left.right;
                            }
                            left.right = cur.right.left;
                        }
                        cur.right.left = cur.left;
                    } 
                }
                
                if (pre != null){
                    if (pre.left == cur){
                        pre.left = replaceNode;
                    } else {
                        pre.right = replaceNode;
                    }
                } else {
                    root = replaceNode;
                }
            }
            return root;
        }
    }
    

Log in to reply
 

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