BST Mock

700,98

 530,501,236

235,701,450

669,108,538

700. Search in a Binary Search Tree

Easy

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null || root.val == val) {
            return root;
        }
        if (val < root.val) {
            return searchBST(root.left, val);
        } else {
            return searchBST(root.right, val);
        }
    }
}

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null) {
            return null;
        }
        while (root != null) {
            if (val < root.val) {
                root = root.left;
            } else if (val > root.val) {
                root = root.right;
            } else {
                return root;
            }
        }
        return null;
    }
}
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null || root.val == val) {
            return root;
        }
        TreeNode left = searchBST(root.left, val);
        if (left != null) {
            return left;
        }
        return searchBST(root.right, val);
    }
}

98. Validate Binary Search Tree

Medium

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

valid BST is defined as follows:

  • 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.
class Solution {
    long pre = Long.MIN_VALUE;

    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        boolean left = isValidBST(root.left);
        if (!left) {
            return false;
        }
        if (pre >= root.val) {
            return false;
        }
        pre = root.val;
        boolean right = isValidBST(root.right);
        return right;
    }
}

class Solution {
    long pre = Long.MIN_VALUE;

    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        boolean left = isValidBST(root.left);
        if (pre >= root.val) {
            return false;
        }
        pre = root.val;
        boolean right = isValidBST(root.right);
        return left && right;
    }
}
class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return false;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        Long pre = Long.MIN_VALUE;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                TreeNode pop = stack.pop();
                if (pre >= pop.val) {
                    return false;
                }
                pre = (long) pop.val;
                cur = pop.right;
            }
        }
        return true;
    }
}

530. Minimum Absolute Difference in BST

Easy

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

class Solution {
    public int getMinimumDifference(TreeNode root) {
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        TreeNode pre = null;
        int ans = Integer.MAX_VALUE;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                TreeNode pop = stack.pop();
                if (pre != null) {
                    ans = Math.min(pop.val - pre.val, ans);
                }
                pre = pop;
                cur = pop.right;
            }
        }
        return ans;
    }
}
class Solution {
    int ans = Integer.MAX_VALUE;
    TreeNode pre = null;

    public int getMinimumDifference(TreeNode root) {
        if (root == null) {
            return 0;
        }
        getMinimumDifference(root.left);
        if (pre != null) {
            ans = Math.min(ans, root.val - pre.val);
        }
        pre = root;
        getMinimumDifference(root.right);
        return ans;
    }
}

501. Find Mode in Binary Search Tree

Easy

Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.

If the tree has more than one mode, return them in any order.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.
class Solution {
    public int[] findMode(TreeNode root) {
        int count = 0;
        int maxCount = 0;
        TreeNode pre = null;
        List<Integer> list = new LinkedList<>();
        if (root == null) {
            return null;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                if (pre != null) {
                    if (pre.val == cur.val) {
                        count = count + 1;
                    } else {
                        count = 1;
                    }
                } else {
                    count = 1;
                }
                if (count > maxCount) {
                    maxCount = count;
                    list.clear();
                    list.add(cur.val);
                } else if (count == maxCount) {
                    list.add(cur.val);
                }
                pre = cur;
                cur = cur.right;
            }
        }
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
}

class Solution {
    public int[] findMode(TreeNode root) {
        int count = 0;
        int maxCount = 0;
        TreeNode pre = null;
        List<Integer> list = new LinkedList<>();
        if (root == null) {
            return null;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                if (pre == null || cur.val != pre.val) {
                    count = 1;
                } else {
                    count++;
                }
                if (count > maxCount) {
                    maxCount = count;
                    list.clear();
                    list.add(cur.val);
                } else if (count == maxCount) {
                    list.add(cur.val);
                }
                pre = cur;
                cur = cur.right;
            }
        }
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
}

236. Lowest Common Ancestor of a Binary Tree

Medium

Topics

Companies

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) { // 递归结束条件
            return root;
        }

        // 后序遍历
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);

        if(left == null && right == null) { // 若未找到节点 p 或 q
            return null;
        }else if(left == null && right != null) { // 若找到一个节点
            return right;
        }else if(left != null && right == null) { // 若找到一个节点
            return left;
        }else { // 若找到两个节点
            return root;
        }
    }
}

235. Lowest Common Ancestor of a Binary Search Tree

Medium

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        while (root != null) {
            if(root.val<p.val&&root.val<q.val){
                root = root.right;
            }else if(root.val>p.val&&root.val>q.val){
                root = root.left;
            }else {
               break;
            }
        }
        return root;
    }
}
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
        if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
        return root;
    }
}

701. Insert into a Binary Search Tree

Medium

You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        if (val < root.val) {
            root.left = insertIntoBST(root.left, val);
        } else if (val > root.val) {
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }
}
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        TreeNode curNode = root;
        TreeNode pre = root;
        while (curNode != null) {
            pre = curNode;
            if (val < curNode.val) {
                curNode = curNode.left;
            } else if (val > curNode.val) {
                curNode = curNode.right;
            } else {
                return root;
            }
        }
        if (val < pre.val) {
            pre.left = new TreeNode(val);
        } else {
            pre.right = new TreeNode(val);
        }
        return root;
    }
}

450. Delete Node in a BST

Medium

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:

  1. Search for a node to remove.
  2. If the node is found, delete the node.
class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return root;
        if (root.val == key) {
            if (root.right == null) {
                return root.left;
            } else {
                TreeNode cur = root.right;
                while (cur.left != null) {
                    cur = cur.left;
                }
                cur.left = root.left;
                root = root.right;
                return root;
            }
        }
        if (key < root.val) root.left = deleteNode(root.left, key);
        if (key > root.val) root.right = deleteNode(root.right, key);
        return root;
    }
}
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;
            if (root.right == null) return root.left;
            TreeNode tmp = root.right;
            while (tmp.left != null) {
                tmp = tmp.left;
            }
            root.val = tmp.val;
            root.right = deleteNode(root.right,tmp.val);
        }
        return root;
    }
}
class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        //1.找到待删除节点
        //2.只有一个孩子的情况,直接托付给父节点。编写托孤方法
        //3.左右孩子都没有用2里的处理逻辑就可以了
        //4.左右孩子都有
        //左右孩子都有,则找到待删除节点的后继节点,记为S,其父节点记为SP
        //若S与待删除节点相邻,即后继节点是他的孩子,则直接将后继孩子节点S继承自己位置,将S托付给Parent
        //若后继节点不是他的孩子,则先把这个孩子节点的孩子托付给这个孩子的父亲SP,再让这个孩子顶替自己位置
        if (root == null) {
            return null;
        }
        TreeNode curNode = root;
        TreeNode parentNode = null;
        //找到需要删除的节点
        while (curNode != null) {
            if (key < curNode.val) {
                parentNode = curNode;
                curNode = curNode.left;
            } else if (key > curNode.val) {
                parentNode = curNode;
                curNode = curNode.right;
            } else {
                break;
            }
        }
        //没有找到
        if (curNode == null) {
            return root;
        }
        //如果只有一个孩子,直接把孩子托付给父节点(所以要记录父节点)
        if (curNode.left == null || curNode.right == null) {
            TreeNode newChild = (curNode.left == null) ? curNode.right : curNode.left;
            if (parentNode == null) {
                root = newChild;  // 这里处理如果删除的是根节点的情况
            } else {
                shift(parentNode, curNode, newChild);
            }
        } else {
            //左右孩子都有
            //4.1找到删除节点的后继(findPrePost里有),这里一定有右子树,所以找后继的代码用不完
            TreeNode s = curNode.right;
            TreeNode sParent = curNode;
            while (s.left != null) {
                sParent = s;
                s = s.left;
            }
            //4.2后继节点不是待删除节点的孩子,则需要先处理掉后继节点的孩子,再让他继承
            if (curNode.right != s) {
                shift(sParent, s, s.right);//不可能是s.left因为代码如果能执行到这里,就只会有右孩子,因为s.left比s更小
                s.right = curNode.right;
            }
            //4.3后继节点取代被删除节点
            if (parentNode == null) {
                root = s;
            } else {
                shift(parentNode, curNode, s);
            }
            s.left = curNode.left;//之前没有左孩子,现在有左孩子,顶替掉的要长兄如父

        }
        return root;
    }

    //编写一个托孤方法
    //将待删除节点的孩子节点托付给父节点,顶替掉自己的位置
    private void shift(TreeNode parentNode, TreeNode deleteNode, TreeNode child) {
        if (deleteNode == parentNode.left) {
            parentNode.left = child;
        } else {
            parentNode.right = child;
        }
    }
}

669. Trim a Binary Search Tree

Medium

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.

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) {
            return null;
        }
        while (root != null && (root.val < low || root.val > high)) {
            if (root.val < low) {
                root = root.right;
            } else if (root.val > high) {
                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;
    }
}
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;
    }
}

108. Convert Sorted Array to Binary Search Tree

Easy

Given an integer array nums where the elements are sorted in ascending order, convert it to a 

height-balanced

 binary search tree.

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        TreeNode root = traversal(nums, 0, nums.length - 1);
        return root;
    }
    private TreeNode traversal(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }
        int mid = (left + right) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = traversal(nums, left, mid - 1);
        root.right = traversal(nums, mid + 1, right);
        return root;
    }
}

538. Convert BST to Greater Tree

Medium

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.
class Solution {
    int pre = 0;
    int sum = 0;

    public TreeNode convertBST(TreeNode root) {
        inorderTraversal(root);
        return root;
    }

    private void inorderTraversal(TreeNode root) {
        if (root == null) {
            return;
        }
        inorderTraversal(root.right);
        sum = pre + root.val;
        pre = sum;
        root.val = sum;
        inorderTraversal(root.left);
    }
}
class Solution {
    public TreeNode convertBST(TreeNode root) {
         if (root == null) {
            return null;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        int sum = 0;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.right;
            } else {
                cur = stack.pop();
                sum = sum + cur.val;
                cur.val = sum;
                cur = cur.left;
            }
        }
        return root;
    }
}

  • 27
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
BST(Binary Search Tree)是一种常见的搜索数据结构,它具有以下特点: - 每个节点最多有两个子节点:左子节点和右子节点。 - 左子节点的值小于等于父节点的值,右子节点的值大于父节点的值。 - 对于每个节点,其左子树和右子树都是二叉搜索树。 以下是一个用Python实现的BST示例: ```python class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BST: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) else: self._insert_recursive(self.root, value) def _insert_recursive(self, node, value): if value < node.value: if node.left is None: node.left = Node(value) else: self._insert_recursive(node.left, value) else: if node.right is None: node.right = Node(value) else: self._insert_recursive(node.right, value) def search(self, value): return self._search_recursive(self.root, value) def _search_recursive(self, node, value): if node is None or node.value == value: return node elif value < node.value: return self._search_recursive(node.left, value) else: return self._search_recursive(node.right, value) ``` 你可以使用该BST类来创建一个二叉搜索树,并进行插入和搜索操作。例如: ```python bst = BST() bst.insert(5) bst.insert(3) bst.insert(7) bst.insert(1) bst.insert(4) print(bst.search(3)) # 输出: <__main__.Node object at 0x...> ``` 希望以上代码能帮到你!如果有任何疑问,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值