题目描述:
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:
1
\
3
/
2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.
解题思路:
这个问题和LeetCode的783. Minimum Distance Between BST Nodes可以说是同一个题,解法也如出一辙。
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int getMinimumDifference(TreeNode root) {
inOrder(root);
int result = Math.abs((int)arraylist.get(0) - (int)arraylist.get(1));
for(int i=0;i<arraylist.size()-1;i++){
if(result >= Math.abs((int)arraylist.get(i) - (int)arraylist.get(i+1))){
result = Math.abs((int)arraylist.get(i) - (int)arraylist.get(i+1));
System.out.println("result---"+result);
}
}
return result;
}
List arraylist = new ArrayList<Integer>();
int index = 0;
public void inOrder(TreeNode node){
if(node == null){
return;
}
inOrder(node.left);
System.out.println(node.val);
arraylist.add(index++,node.val);
inOrder(node.right);
}
}