LeetCode刷題 - - 樹(六)二叉搜索樹

二叉搜索樹

二叉搜索樹,左子結點小於根結點小於右子節點。

遞歸怎麼寫?
1.總結規律,你知道你是在寫一個遞歸方法,那麼就得定義出這個遞歸方法是幹什麼的。
2.調用自己
3.跳出條件,跳出時的判斷條件是什麼以及當前條件下該返回什麼。
需要注意的是,如果你的跳出條件有問題的話,遞歸很容易產生stackoverflow。

669. 修剪二叉搜索樹

給定一個二叉搜索樹,同時給定最小邊界L 和最大邊界 R。通過修剪二叉搜索樹,使得所有節點的值在[L, R]中 (R>=L) 。你可能需要改變樹的根節點,所以結果應當返回修剪好的二叉搜索樹的新的根節點。

示例 1:

輸入: 
    1
   / \
  0   2

  L = 1
  R = 2

輸出: 
    1
      \
       2
示例 2:

輸入: 
    3
   / \
  0   4
   \
    2
   /
  1

  L = 1
  R = 3

輸出: 
      3
     / 
   2   
  /
 1
//BST 二叉查找樹,根節點大於左結點,小於右結點
//對樹進行遍歷,去分析哪些值需要被剪掉,哪些被保留
class Solution {
    public TreeNode trimBST(TreeNode root, int L, int R) {
    if (root == null) return root;
    if (root.val > R) return trimBST(root.left, L, R); //比R大,向左修減
    if (root.val < L) return trimBST(root.right, L, R);//向右修剪
        //兩邊修剪,存在在【R,L】區間範圍內
        root.left = trimBST(root.left, L, R);
        root.right = trimBST(root.right, L, R);
        return root;
    }
}

230. 二叉搜索樹

給定一個二叉搜索樹,編寫一個函數 kthSmallest 來查找其中第 k 個最小的元素。
說明:
你可以假設 k 總是有效的,1 ≤ k ≤ 二叉搜索樹元素個數。

示例 1:

輸入: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
輸出: 1
示例 2:

輸入: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
輸出: 3

二叉搜索樹的中序就是一個從小到大排序的序列,因此這道題可以通過中序遍歷來做。

//第k個最小的元素
 //中序遍歷 利用二叉搜索樹的性質排列
 //從小到大排列
class Solution {
    public int kthSmallest(TreeNode root, int k) {
    Stack<TreeNode> stack = new Stack<>();
    while(true){
        while(root != null){
            stack.push(root);
            root = root.left;
        }
        root = stack.pop();
        if(--k == 0) return root.val;
        root = root.right;
    }
}
}

538. 把二叉搜索樹轉換成累加樹

給定一個二叉搜索樹(Binary Search Tree),把它轉換成爲累加樹(Greater Tree),使得每個節點的值是原來的節點值加上所有大於它的節點值之和。

輸入: 二叉搜索樹:
              5
            /   \
           2     13

輸出: 轉換爲累加樹:
             18
            /   \
          20     13
//此題是將大於自身結點的值都累計相加
 //相當於遍歷整棵樹,先遍歷右-中-左
 //變形的中序遍歷
class Solution {
    //定義一個變量來記錄走過的結點的和
    public int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        traver(root);
        return root;
    }
    //定義一個函數
    private void traver(TreeNode node){
       if(node == null) return;
       traver(node.right);
       sum += node.val;//將走過的結點累計相加
       node.val = sum;
       traver(node.left);
    }
}

公共祖先

235. 二叉搜索樹的公共祖先

給定一個二叉搜索樹, 找到該樹中兩個指定節點的最近公共祖先。

百度百科中最近公共祖先的定義爲:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示爲一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。”

例如,給定如下二叉搜索樹: root = [6,2,8,0,4,7,9,null,null,3,5]
在這裏插入圖片描述

//因爲該樹爲二叉搜索樹,只要p和q在同一顆子樹上就一直沿着這顆子樹往下走
 //(這意味着p和q都同時大於或者小於當前指向的根結點)。
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    //找合適的位置,把它放進去
    TreeNode pointer = root;
    while(pointer != null){
      if(pointer.val > p.val && pointer.val > q.val){
        pointer = pointer.left;
    }else if(pointer.val < p.val && pointer.val < q.val){
        pointer = pointer.right;
    }else{
         return pointer;
    }
    }
        return pointer;
    }
}

236. 二叉樹的最近公共祖先

給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。

百度百科中最近公共祖先的定義爲:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示爲一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。”

例如,給定如下二叉樹: root = [3,5,1,6,2,0,8,null,null,7,4]

在這裏插入圖片描述
示例 1:
輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
輸出: 3
解釋: 節點 5 和節點 1 的最近公共祖先是節點 3。

示例 2:
輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
輸出: 5
解釋: 節點 5 和節點 4 的最近公共祖先是節點 5。因爲根據定義最近公共祖先節點可以爲節點本身。

class Solution {
    //功能:給定p和q,如果p和q存在,就返回最近的公共結點,
    //如果只有一個存在,那就返回那一個,如果都不存在,就返回空
   
    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)  return right;//都在右邊
      if(right == null)  return left;//都在左邊

      if(left != null && right != null) return root;//分散在兩邊

      return null;
    }
   
}

轉換成二叉搜索樹

108. 將有序數組轉換成二叉搜索樹

將一個按照升序排列的有序數組,轉換爲一棵高度平衡二叉搜索樹。

本題中,一個高度平衡二叉樹是指一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 1。

給定有序數組: [-10,-3,0,5,9],

一個可能的答案是:[0,-3,9,-10,null,5],它可以表示下面這個高度平衡二叉搜索樹:

      0
     / \
   -3   9
   /   /
 -10  5

//以中間結點爲根節點,遞歸構建左右子數;
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return BST(nums, 0 ,nums.length-1);
    }
    public TreeNode BST(int[] nums, int l, int r){
        if(l > r)  return null;
        
        int mid = (l+r)/2;
        TreeNode root = new TreeNode(nums[mid]);

        //向左遞歸
        root.left = BST(nums, l , mid-1);
        //向右遞歸
        root.right = BST(nums, mid+1 ,r);

        return root;

    }
}

109. 將有序鏈表轉換成二叉搜索樹

給定一個單鏈表,其中的元素按升序排序,將其轉換爲高度平衡的二叉搜索樹。

本題中,一個高度平衡二叉樹是指一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 1。

示例:

給定的有序鏈表: [-10, -3, 0, 5, 9],

一個可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面這個高度平衡二叉搜索樹:

      0
     / \
   -3   9
   /   /
 -10  5

109題和108題不同的是,108題是將一個有序數組轉換成二叉搜索,109題是將有序鏈表轉換成二叉搜索樹,有序數組的中間值很好找,而鏈表的中間值則需要通過快慢指針來找到

class Solution {
    public TreeNode sortedListToBST(ListNode head) {
      if(head == null) return null;
      return buildBST(head, null);
    }
    
    public TreeNode buildBST(ListNode head, ListNode tail){
        if(head == null || head == tail)  return null;

        ListNode fast = head;
        ListNode slow = head;
        
        //注意這裏是tail
        while(fast != tail && fast.next != tail){
            fast = fast.next.next;
            slow = slow.next;
        }
        TreeNode root = new TreeNode(slow.val);
        root.left = buildBST(head, slow);
        root.right = buildBST(slow.next, tail);
        return root;    
    }
}

653. 兩數之和 IV – 輸入BST

給定一個二叉搜索樹和一個目標結果,如果 BST 中存在兩個元素且它們的和等於給定的目標結果,則返回 true。

案例 1:

輸入: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

輸出: True
案例 2:

輸入: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 28

輸出: False

class Solution {
    public boolean findTarget(TreeNode root, int k) {
        List<Integer> list = new ArrayList<>();
        inOrder(root, list);
        int i = 0;
        int j = list.size()-1;
        while(i<j){
            int sum = list.get(i) + list.get(j);
            if(sum == k) return true;
            else if(sum < k) i++;
            else j--;
        }
        return false;

    }
    public void inOrder(TreeNode root, List<Integer> list){
         if(root == null) return;
         inOrder(root.left, list);
         list.add(root.val);
         inOrder(root.right, list);
    }
}

530. 二叉搜索樹的絕對最小值之差

給定一個所有節點爲非負值的二叉搜索樹,求樹中任意兩節點的差的絕對值的最小值

輸入:

   1
    \
     3
    /
   2

輸出:
1

解釋:
最小絕對差爲1,其中 21 的差的絕對值爲 1(或者 23)。
class Solution {
    
    public int getMinimumDifference(TreeNode root) {
    List<Integer> list = new ArrayList<>();
    inOrder(root, list);
    int minDiff = Integer.MAX_VALUE;
    //使其最小值無窮大,然後用其它值去更新最小值
    //排好序的二叉搜索樹,差最小的兩個點必然相鄰;
    for(int i = 1; i < list.size(); i++){
        minDiff = Math.min(minDiff, list.get(i) - list.get(i-1));
    }
    return minDiff;
    }

    public void inOrder(TreeNode node, List<Integer> list){
        if(node == null) return;
        inOrder(node.left, list);
        list.add(node.val);
        inOrder(node.right, list);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章