代码随想录day23| 二叉树part09(669、108、538)

103 阅读3分钟

669. 修剪二叉搜索树

给你二叉搜索树的根节点 root ,同时给定最小边界low 和最大边界 high。通过修剪二叉搜索树,使得所有节点的值在[low, high]中。修剪树 不应该 改变保留在树中的元素的相对结构 (即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在 唯一的答案 。

所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。

 

示例 1:

输入: root = [1,0,2], low = 1, high = 2
输出: [1,null,2]

示例 2:

输入: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
输出: [3,2,null,1]

思路:

  1. node 在区间内 ,处理node的左右节点
  2. node 比区间小,返回node的右子树
  3. node 比区间大,返回node的左子树

返回root.right时等于删除root和root.left ,直接给root赋值那left没删掉

/**
* @param {TreeNode} root
* @param {number} low
* @param {number} high
* @return {TreeNode}
*/
var trimBST = function (root, low, high) {
   if (root === null) return null
   if (root.val > high) {
       return trimBST(root.left, low, high) 
   } 
    if (root.val < low) {
      return  trimBST(root.right, low, high)
   }
       root.left  = trimBST(root.left, low, high)
       root.right = trimBST(root.right, low, high)
   
   return root
};

108. 将有序数组转换为二叉搜索树

给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。

高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。

 

示例 1:

输入: nums = [-10,-3,0,5,9]
输出: [0,-3,9,-10,null,5]
解释: [0,-10,5,null,-3,null,9] 也将被视为正确答案:

示例 2:

输入: nums = [1,3]
输出: [3,1]
解释: [1,null,3][3,1] 都是高度平衡二叉搜索树。

思路

寻找分割点,分割点作为当前节点,然后递归左区间和右区间,高度平衡二叉树,分割点就是数组中间位置的节点。

/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
 const buildTree = (nums, start, end) => {
     if(start > end) return null
     const midIndex = Math.floor((start + end)/2)
     const root = new TreeNode(nums[midIndex])
     root.left = buildTree(nums, start ,midIndex -1)
     root.right = buildTree(nums, midIndex +1,end)
     return root
 }
var sortedArrayToBST = function(nums) {
    return buildTree(nums, 0 ,nums.length -1)
};

538. 把二叉搜索树转换为累加树

给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

提醒一下,二叉搜索树满足下列约束条件:

  • 节点的左子树仅包含键 小于 节点键的节点。
  • 节点的右子树仅包含键 大于 节点键的节点。
  • 左右子树也必须是二叉搜索树。

注意: 本题和 1038: leetcode-cn.com/problems/bi… 相同

 

示例 1:

输入: [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
输出: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]

示例 2:

输入: root = [0,null,1]
输出: [1,null,1]

示例 3:

输入: root = [1,0,2]
输出: [3,3,2]

示例 4:

输入: root = [3,2,4,1]
输出: [7,9,4,10]

思路

使用右中左的顺序遍历,每个遍历到的节点的值为 当前节点值+上一个节点的值

/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var convertBST = function (root) {
    let pre = 0
    const reInOrder = (root) => {
        if (root === null) return null
        reInOrder(root.right)
        root.val = pre + root.val
        pre = root.val
        reInOrder(root.left)
    }
    reInOrder(root)
    return root
};