2018年6月14日 星期四

[LeetCode] 783. Minimum Distance Between BST Nodes

轉自LeetCode

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.
<Solution>

想法如下
  • 用 inorder 的方式歷遍 BST,因為是 BST,所以結果會是 sorted 的
  • 在歷遍的同時,紀錄前一個數字,並計算當前數字減掉前一個數字,是不是最小值
  • 只要計算 “當前數字減掉前一個數字” 是因為歷遍結果是 sorted 的,加上是要找最小值,所以只要檢查相鄰兩個數就可以了
code 如下

Java(參考解答)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Integer mPrv = null;
Integer mMin = Integer.MAX_VALUE;
public int minDiffInBST(TreeNode root) {
inorder(root);
return mMin;
}
private void inorder(TreeNode root) {
if(root == null) {
return;
}
inorder(root.left);
if(mPrv != null) {
mMin = Math.min(mMin, root.val - mPrv);
}
mPrv = root.val;
inorder(root.right);
}
}

沒有留言:

張貼留言