LeetCode | 669. Trim a BST, 108. Convert Sorted Array to BST, 538. Convert BST to Greater Tree

669. Trim a Binary Search Tree

Link: https://leetcode.com/problems/trim-a-binary-search-tree/

Description

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node’s descendant should remain a descendant). It can be proven that there is a unique answer.

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

Approach

Recursion

  • If root equals to null, return null.
  • If the value of root less than low, call the function on the right subtree and return it.
  • If the value of root greater than high, call the function on the left subtree and return it.
  • If the value of root is valid, call the function on the left subtree and rightsubtree to check whether the rest of the nodes are valid.
  • Return the `root``

Iteration

  • While root is not null, and the value of the root is not in [low, high]:
    • If the value of root less than low, set the right subtree of root to root.
    • If the value of root greater than high, set the left subtree of root to root.
  • Initialiaze a variable cur with value root.
  • While cur is not null:
    • While the value of the left subtree less than low:
      • Set the right subtree of the left subtree to left subtree.
    • Set the left subtree of cur to cur.
  • Reset root to cur.
  • While cur is not null:
    • While the value of the right subtree greater than high:
      • Set the left subtree of the right subtree to right subtree.
    • Set the right subtree of cur to cur.
  • Return root.
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
// Recursion
class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null)
            return null;
        
        if (root.val < low)
            return trimBST(root.right, low, high);
        if (root.val > high)
            return trimBST(root.left, low, high);
        
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        return root;
    }
}

// Iteration
class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        while (root != null && (root.val < low || root.val > high)) {
            if (root.val < low)
                root = root.right;
            else
                root = root.left;
        }

        TreeNode cur = root;
        while (cur != null) {
            while (cur.left != null && cur.left.val < low)
                cur.left = cur.left.right;
            cur = cur.left;
        }

        cur = root;
        while (cur != null) {
            while (cur.right != null && cur.right.val > high)
                cur.right = cur.right.left;
            cur = cur.right;
        }

        return root;
    }
}

108. Convert Sorted Array to Binary Search Tree

Link: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

Description

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

Approach

  • Create a recursive function with parameters num, start and end, the last two parameters are used to denote the start and end of the processing subarray.
  • If start larger than or equal to end, which means the subarray is empty, return null.
  • Find the middle point of the subarray and initialize a node with the value of middle point.
  • Call the function with updated start and end to create the left subtree (the subarray before the middle point) and right subtree (the subarray after the middle point) of the node.
  • Return the node.

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return createBST(nums, 0, nums.length);
    }

    private TreeNode createBST(int[] nums, int start, int end) {
        if (start >= end)
            return null;
        int mid = (start + end) / 2;
        TreeNode node = new TreeNode(nums[mid]);
        node.left = createBST(nums, start, mid);
        node.right = createBST(nums, mid + 1, end);
        return node;
    }
}

538. Convert BST to Greater Tree

Link: https://leetcode.com/problems/convert-bst-to-greater-tree/

Description

Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.

As a reminder, a binary search tree is a tree that satisfies these constraints:

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.

Approach

Recursion

  • Initialize a global variable preVal (denotes the sum value of previous nodes) to 0.
  • If root is null, return null.
  • Recursively call on the right subtree of root.
  • Add the value of root with preVal and set the value of root to preVal.
  • Recursively call on the left subtree of root.
  • return root.

Iteration

  • If root is null, return null.
  • Initialize a TreeNode stack, TreeNode cur (denotes the ) to root and preVal (denotes the sum value of previous nodes) to 0.
  • While the stack is not empty or cur is not null:
    • If cur is not null, push cur to the stack and point cur to its right child.
    • Else, pop the top of the stack to cur. Add preVal to the value of cur and then set the new value of cur to preVal. Point cur to its left child.
  • Return root.

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
// Recusion
class Solution {
    int preVal = 0;
    public TreeNode convertBST(TreeNode root) {
        if (root == null)
            return null;
        convertBST(root.right);
        root.val += preVal;
        preVal = root.val;
        convertBST(root.left);
        return root;
    }
}

// Iteration
class Solution {
    public TreeNode convertBST(TreeNode root) {
        if (root == null)
            return root;
        Stack<TreeNode> stack = new Stack<>();
        int preVal = 0;
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.right;
            }
            else {
                cur = stack.pop();
                cur.val += preVal;
                preVal = cur.val;
                cur = cur.left;
            }
        }
        return root;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值