Delete a node from BST.
1 public class ZigzagIterator { 2 3 public void inorder(TreeNode root) { 4 if (root != null) { 5 inorder(root.left); 6 System.out.println(root.val + " "); 7 inorder(root.right); 8 } 9 } 10 11 public TreeNode delete(TreeNode root, int val) { 12 if (root == null) 13 return root; 14 15 if (root.val > val) { 16 root.left = delete(root.left, val); 17 } else if (root.val < val) { 18 root.right = delete(root.right, val); 19 } else { 20 if (root.left == null && root.right == null) { 21 return null; 22 } else if (root.left == null) { 23 return root.right; 24 } else if (root.right == null) { 25 return root.left; 26 } else { 27 root.val = findMin(root.right).val; 28 root.right = delete(root.right, root.val); 29 } 30 } 31 return root; 32 } 33 34 public TreeNode findMin(TreeNode n) { 35 if (n.left != null) { 36 return findMin(n.left); 37 } 38 return n; 39 } 40 41 } 42 43 class TreeNode { 44 TreeNode left; 45 TreeNode right; 46 int val; 47 48 public TreeNode(int i) { 49 val = i; 50 } 51 }
时间: 2024-12-09 23:41:39