LeetCode[450]Delete Node in a BST(Java)
来源:互联网 发布:matlab 定义二维数组 编辑:程序博客网 时间:2024/06/10 15:07
Description:
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
Solution:
Recursive递归
首先查找到val=key节点的所在位置,在查找的过程中,利用递归重建BST。
查找到之后,需要将当前节点重新赋值,然后重新构建右子树,方式是将右子树的最左叶结点的值付给当前节点,然后删除该最左叶结点。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public TreeNode deleteNode(TreeNode root, int key) { if(root == null){ return null; } if(root.val > key){ root.left = deleteNode(root.left, key); }else if(root.val < key){ root.right = deleteNode(root.right, key); }else{ if(root.left == null){ return root.right; }else if(root.right == null){ return root.left; } TreeNode temp = search(root.right); root.val = temp.val; root.right = deleteNode(root.right, temp.val); } return root; } public TreeNode search(TreeNode node){ while(node.left != null){ node = node.left; } return node; }}
阅读全文
0 0
- LeetCode[450]Delete Node in a BST(Java)
- [LeetCode]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
- [python]leetcode(450). Delete Node in a BST
- 450 Delete Node in a BST
- LeetCode 450 Delete Node in a BST(删除BST节点)
- Delete Node in a BST
- Delete Node in a BST
- Delete Node in a BST
- leetcode-450.delete a node in a BST
- Ubuntu 14.04 LTS 安装jdk1.8.0_91
- Navicat for MySQL安装及破解
- Redis 在window和linux下的安装
- csv用excel打开数据都在第一列解决办法
- 驱动开发 环境搭建(VS2008+WDK+DDKWzard)
- LeetCode[450]Delete Node in a BST(Java)
- js递归实现树形目录
- spark-通过StructType直接指定Schema
- 21、C#里面类的创建和使用
- [分享]利用QuadSPI外扩串行NOR Flash的实现
- Spring学习笔记
- 设计模式 适配器模式
- 数组元素是json对象的去重方法
- spring boot项目实战之公共代码抽取