450. Delete Node in a BST

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     TreeNode findMin(TreeNode root)
12     {
13         while(root.left!=null)
14             root=root.left;
15         return root;
16     }
17     public TreeNode deleteNode(TreeNode root, int key) {
18         if(null==root)return null;
19         if(key<root.val)
20             root.left=deleteNode(root.left,key);
21         else if(key>root.val)
22             root.right=deleteNode(root.right,key);
23         else
24         {
25         if(null==root.left)
26             return root.right;
27         else if(null==root.right)
28             return root.left;
29         
30         TreeNode min=findMin(root.right);
31         root.val=min.val;
32         root.right=deleteNode(root.right,min.val);
33         }
34         return root;
35     }
36 }

 

上一篇:C语言推箱子


下一篇:大二下周总结(13)