Leetcode 450. Delete Node in a BST 删除BST中的节点 解题报告
来源:互联网 发布:家装造价师软件 编辑:程序博客网 时间:2024/06/06 06:42
1 解题思想
现在有一个二叉搜索树,现在要让你删除一个节点,并且保证整个BST的性质不变。
要保证整个性质,我们必须在删除的位置上,找一个合适的值来进行替换,使得BST上的每个节点都满足 当前节点的值大于左节点但是小于右节点
而替换策略就是:
1、当前删除位置,用左边子树的最大值的节点替换
2、或者是,用右边子树的最小值的节点替换
用上面的策略就可以保证删除后性质不变,并且调整开销也很少
2 原题
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.Basically, the deletion can be divided into two stages:Search for a node to remove.If the node is found, delete the node.Note: Time complexity should be O(height of tree).Example:root = [5,3,6,2,4,null,7]key = 3 5 / \ 3 6 / \ \2 4 7Given key to delete is 3. So we find the node with value 3 and delete it.One valid answer is [5,4,6,2,null,null,7], shown in the following BST. 5 / \ 4 6 / \2 7Another valid answer is [5,2,6,null,4,null,7]. 5 / \ 2 6 \ \ 4 7
3 AC解
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int findReplacement(TreeNode parent,TreeNode node,boolean isLeft){ if(node.right == null){ if (isLeft) parent.left = node.left; else parent.right = node.left; return node.val; } return findReplacement(node,node.right,false); } public TreeNode deleteNode(TreeNode root, int key) { if(root==null) return null; if(root.val == key){ if(root.left == null) return root.right; if(root.right == null) return root.left; root.val = findReplacement(root,root.left,true); // 选择左边最大的,或者右边最小的 } else{ if(root.val > key) root.left = deleteNode(root.left,key); else root.right = deleteNode(root.right,key); } return root; }}
0 0
- Leetcode 450. Delete Node in a BST 删除BST中的节点 解题报告
- [leetcode] 450. Delete Node in a BST 解题报告
- [Leetcode] 450. Delete Node in a BST 解题报告
- LeetCode 450 Delete Node in a BST(删除BST节点)
- LeetCode 450. Delete Node in a BST
- LeetCode 450. Delete Node in a BST
- Leetcode-450. Delete Node in a BST
- 【LeetCode】 450. Delete Node in a BST
- [LeetCode]450. Delete Node in a BST
- LeetCode 450. Delete Node in a BST
- LeetCode 450.Delete Node in a BST
- leetcode 450. Delete Node in a BST
- [LeetCode] 450. Delete Node in a BST
- leetcode 450. Delete Node in a BST 二叉搜索树BST删除结点
- [LeetCode]Delete Node in a BST
- leetcode-450.delete a node in a BST
- 【二叉树】二分查找树,节点删除【Add to List 450. Delete Node in a BST】
- LeetCode Peoject 450.Delete Node in a BST
- 关于web service与cxf的拦截器
- *[Lintcode]Median of two Sorted Arrays
- 不良资产回收处置创新方式
- 值类型引用类型
- Failed to create SD card - Android Studio
- Leetcode 450. Delete Node in a BST 删除BST中的节点 解题报告
- 将Mule ESB Http项目转换为Tomcat项目(4) 将ESB项目改造为Web项目
- $_POST取不到值的原因
- 如何正确bootbox加载echarts图表
- 将Zookeeper集成到你的应用中
- 超简易,极基础,巨详细的SSM(Spring +Springmvc+Mybatis)框架整合搭建2.0版
- Android 系统服务管家servicemanager启动过程详解
- 使用MAT工具分析性能
- 分治——最小点对(HDU 1007)