码迷,mamicode.com
首页 > 其他好文 > 详细

Delete a node from BST

时间:2016-08-07 06:24:03      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Delete a node from BST

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5745353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!