二叉查找树 (BST)

二叉查找树(BST):根节点大于等于左子树所有节点,小于等于右子树所有节点。

二叉查找树中序遍历有序。

中序遍历一棵二叉搜索树的结果是得到一个升序序列。

例题:

1.修剪二叉搜索树

class Solution {
    public TreeNode trimBST(TreeNode root, int L, int R) {
       return helper(root,L,R); 
    }
    private TreeNode helper(TreeNode root, int L, int R){
        if (root==null) return root;
        if (root.val<L) return helper(root.right,L,R);
        if (root.val>R) return helper(root.left,L,R);
        root.left=helper(root.left,L,R);
        root.right=helper(root.right,L,R);
        return root;
    }
}
  1. 有序链表转换二叉搜索树
  class Solution {
  
    private List<Integer> values;
  
    public Solution() {
      this.values = new ArrayList<Integer>();
    }
  
    private void mapListToValues(ListNode head) {
      while (head != null) {
        this.values.add(head.val);
        head = head.next;
      }
    }
  
    private TreeNode convertListToBST(int left, int right) {
      // Invalid case
      if (left > right) {
        return null;
      }
  
      // Middle element forms the root.
      int mid = (left + right) / 2;
      TreeNode node = new TreeNode(this.values.get(mid));
  
      // Base case for when there is only one element left in the array
      if (left == right) {
        return node;
      }
  
      // Recursively form BST on the two halves
      node.left = convertListToBST(left, mid - 1);
      node.right = convertListToBST(mid + 1, right);
      return node;
    }
  
    public TreeNode sortedListToBST(ListNode head) {
  
      // Form an array out of the given linked list and then
      // use the array to form the BST.
      this.mapListToValues(head);
  
      // Convert the array to
      return convertListToBST(0, this.values.size() - 1);
    }
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值