该题主要考察二叉树的中序遍历,因为二叉搜索树的特性是左边小于父节点
小于右节点。然后得出一个按顺序排列的数组,比较前后元素之差,得出最小值。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var getMinimumDifference = function(root) {
if(root === null) return null;
let arr = [];
(function getnum(node){
if(node === null){
return false;
}
let left = getnum(node.left);
arr.push(node.val);
let right = getnum(node.right);
})(root);
let minNum = arr[1]-arr[0];
for(let i = 1;i<arr.length;i++){
if(i < arr.length - 1){
if(minNum > arr[i+1] - arr[i]){
minNum = arr[i+1] - arr[i];
}
}
}
return minNum;
};
网友评论