|
| 1 | +/* |
| 2 | + * @lc app=leetcode.cn id=450 lang=java |
| 3 | + * |
| 4 | + * [450] 删除二叉搜索树中的节点 |
| 5 | + */ |
| 6 | + |
| 7 | +// @lc code=start |
| 8 | +/** |
| 9 | + * Definition for a binary tree node. |
| 10 | + * public class TreeNode { |
| 11 | + * int val; |
| 12 | + * TreeNode left; |
| 13 | + * TreeNode right; |
| 14 | + * TreeNode() {} |
| 15 | + * TreeNode(int val) { this.val = val; } |
| 16 | + * TreeNode(int val, TreeNode left, TreeNode right) { |
| 17 | + * this.val = val; |
| 18 | + * this.left = left; |
| 19 | + * this.right = right; |
| 20 | + * } |
| 21 | + * } |
| 22 | + */ |
| 23 | +classSolution { |
| 24 | +publicTreeNodedeleteNode(TreeNoderoot,intkey) { |
| 25 | +returntraverse(root,key); |
| 26 | + } |
| 27 | + |
| 28 | +privateTreeNodetraverse(TreeNoderoot,intkey) { |
| 29 | +if (root ==null) |
| 30 | +returnnull; |
| 31 | +if (root.val ==key) { |
| 32 | +if (root.left ==null &&root.right ==null) |
| 33 | +returnnull; |
| 34 | +if (root.left !=null &&root.right ==null) |
| 35 | +returnroot.left; |
| 36 | +if (root.right !=null &&root.left ==null) |
| 37 | +returnroot.right; |
| 38 | +if (root.left !=null &&root.right !=null) { |
| 39 | +TreeNodetmp =root.right; |
| 40 | +while (tmp.left !=null) { |
| 41 | +tmp =tmp.left; |
| 42 | + } |
| 43 | +tmp.right =deleteNode(root.right,tmp.val); |
| 44 | +tmp.left =root.left; |
| 45 | +returntmp; |
| 46 | + } |
| 47 | + } |
| 48 | +if (root.val >key) { |
| 49 | +root.left =traverse(root.left,key); |
| 50 | + }else { |
| 51 | +root.right =traverse(root.right,key); |
| 52 | + } |
| 53 | +returnroot; |
| 54 | + } |
| 55 | +} |
| 56 | +// @lc code=end |