摘要:解题思路我们可以用递归来查找,在找到需要删除的节点后,我们需要分情况讨论节点是叶子节点,直接返回节点有一个孩子,直接返回孩子节点有两个孩子,我们要将右子树中最小的节点值赋值给根节点,并在右子树中删除掉那个最小的节点。
Delete Node in a BST
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 7 Given 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 7 Another valid answer is [5,2,6,null,4,null,7]. 5 / 2 6 4 7
解题思路
我们可以用递归来查找Key,在找到需要删除的节点后,我们需要分情况讨论:
1) 节点是叶子节点,直接返回null;
2) 节点有一个孩子,直接返回孩子;
3)节点有两个孩子,我们要将右子树中最小的节点值赋值给根节点,并在右子树中删除掉那个最小的节点。
2.代码
public class Solution { public TreeNode deleteNode(TreeNode root, int key) { if(root==null) return root; if(key>root.val) root.right=deleteNode(root.right,key); else if(key
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/69808.html
摘要:解题思路本题需要找的是第小的节点值,而二叉搜索树的中序遍历正好是数值从小到大排序的,那么这题就和中序遍历一个情况。 Kth Smallest Element in a BSTGiven a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You ...
摘要:解题思路平衡二叉树,其实就是数组中间的数作为根,利用递归实现左子树和右子树的构造。 Convert Sorted Array to Binary Search TreeGiven an array where elements are sorted in ascending order, convert it to a height balanced BST. 1.解题思路平衡二叉树,...
Problem 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 divi...
摘要:题目要求假设有一棵二叉搜索树,现在要求从二叉搜索树中删除指定值,使得删除后的结果依然是一棵二叉搜索树。思路和代码二叉搜索树的特点是,对于树中的任何一个节点,一定满足大于其所有左子节点值,小于所有其右子节点值。 题目要求 Given a root node reference of a BST and a key, delete the node with the given key i...
摘要:解题思路这个题目其实就是基于先序遍历,用递归和非递归思想都可以。递归求所有左叶子节点的和,我们可以将其分解为左子树的左叶子和右子树的左叶子和递归结束条件找到左叶子节点,就可以返回该节点的。代码非递归判断是否为左叶子节点递归 Sum of Left LeavesFind the sum of all left leaves in a given binary tree. Example:...
阅读 634·2021-11-23 09:51
阅读 3177·2021-10-11 10:58
阅读 15226·2021-09-29 09:47
阅读 3490·2021-09-01 11:42
阅读 1255·2019-08-29 16:43
阅读 1809·2019-08-29 15:37
阅读 2059·2019-08-29 12:56
阅读 1701·2019-08-28 18:21