今天的题目不难,hhh。过几天做个总结吧,最近还是比较忙。
给你二叉搜索树的根节点 root
,同时给定最小边界low
和最大边界 high
。通过修剪二叉搜索树,使得所有节点的值在[low, high]
中。修剪树 不应该 改变保留在树中的元素的相对结构 (即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在 唯一的答案 。
所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。
func trimBST(root *TreeNode,low,high int)*TreeNode{
if root == nil{
return nil
}
if root.Val <low{//左子树进行删除,更换位该节点的右节点进行遍历
right:= trimBST(root.Right,low,high)
return right
}
if root.Val >high{
left :=trimBST(root.Left,low,high)
return left
}
root.Left = trimBST(root.Left,low,high)
root.Right = trimBST(root.Right,low,high)
return root
}
给你一个整数数组 nums
,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。
高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。
func sortedArrayToBST(nums []int) *TreeNode {
if len(nums)==0{ return nil}
index :=len(nums)/2
root:= &TreeNode{Val:nums[index]}
root.Left =sortedArrayToBST(nums[:index])
root.Right=sortedArrayToBST(nums[index+1:])
return root
}
给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node
的新值等于原树中大于或等于 node.val
的值之和。
提醒一下,二叉搜索树满足下列约束条件:
- 节点的左子树仅包含键 小于 节点键的节点。
- 节点的右子树仅包含键 大于 节点键的节点。
- 左右子树也必须是二叉搜索树。
//累加的顺序是右中左
var preV int
func convertBST(root *TreeNode)*TreeNode{
preV = 0
retrive(root)
return root
}
func retrive(node *TreeNode){
if node ==nil{ return }
retrive(node.Right)
node.Val +=preV
preV =node.Val
retrive(node.Left)
}