1. 程式人生 > >LeetCode刷題783. Minimum Distance Between BST Nodes

LeetCode刷題783. Minimum Distance Between BST Nodes

題目描述:

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

Example :

Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.

The given tree [4,2,6,1,3,null,null] is represented by the following diagram:

          4
        /   \
      2      6
     / \    
    1   3  

while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.

Note:

  1. The size of the BST will be between 2 and 100.
  2. The BST is always valid, each node's value is an integer, and each node's value is different.

 解題思路:

題目是要找出二叉搜尋樹任意兩節點的差的最小值。

二叉搜尋樹這種資料結構,它的左兒子小於父親節點小於右兒子。那麼你會發現,它的中序遍歷其實就是從小到大排序的。

本題需要找出任意兩節點之間的最小值,也就是在考察二叉搜尋樹的中序遍歷。由於樹的特性,用遞迴演算法很容易實現遍歷操作。

程式碼如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int[] arr = new int[1000];
    int ii=0;
    public int minDiffInBST(TreeNode root) {
        inOrder(root);
        int result = Math.abs(arr[0]-arr[1]);
        for(int i=0;i<getSize(arr)-2;i++){
            if(result>Math.abs(arr[i]-arr[i+1])){
                result = Math.abs(arr[i]-arr[i+1]);
                System.out.println(result);
            }
            
        }
        return result;
    }
    
    private int getSize(int[] arr){
        for(int i = 0;i<arr.length; i++){
            if(arr[i]==0){
                return i+1;
            }
        }
        return 0;
    }
    
    private void inOrder(TreeNode node){
        if(node!=null){
            inOrder(node.left);
            arr[ii]=node.val;
            ii++;
            inOrder(node.right);
        }
    }
}