leetcode 算法题783 (简单204) 二叉搜索树结点最小距离
- 题目介绍
给定一个二叉搜索树的根结点 root, 返回树中任意两节点的差的最小值。
- 示例
输入: root = [4,2,6,1,3,null,null]
输出: 1
解释: 注意,root是树结点对象(TreeNode object),而不是数组。给定的树 [4,2,6,1,3,null,null] 可表示为下图:4 / \ 2 6 / \ 1 3
最小的差值是 1, 它是节点1和节点2的差值, 也是节点3和节点2的差值
- 注意
二叉树的大小范围在 2 到 100。
二叉树总是有效的,每个节点的值都是整数,且不重复。
- 解法一
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDiffInBST = function(root) {
let mins = [];
if(root.left) {
mins.push(findMinDiffLeft(root.left, root.val));
}
if(root.right) {
mins.push(findMinDiffRight(root.right, root.val));
}
return Math.min(...mins)
};
const findMinDiffLeft = (node, val) => {
let mins = [val - findMax(node)];
if(node.left) {
mins.push(findMinDiffLeft(node.left, node.val));
}
if(node.right) {
mins.push(findMinDiffRight(node.right, node.val));
}
return Math.min(...mins);
}
const findMinDiffRight = (node, val) => {
let mins = [findMin(node) - val];
if(node.left) {
mins.push(findMinDiffLeft(node.left, node.val));
}
if(node.right) {
mins.push(findMinDiffRight(node.right, node.val));
}
return Math.min(...mins);
}
const findMax = node => {
if(node.right) {
return findMax(node.right);
}
return node.val;
}
const findMin = node => {
if(node.left) {
return findMin(node.left);
}
return node.val;
}
执行用时 : 60 ms, 在所有 JavaScript 提交中击败了100.00%的用户
内存消耗 : 34.5 MB, 在所有 JavaScript 提交中击败了50.00%的用户
- 解法二
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDiffInBST = function(root) {
let mins = [];
if(root.left) {
mins.push(root.val - findMax(root.left));
mins.push(minDiffInBST(root.left));
}
if(root.right) {
mins.push(findMin(root.right) - root.val);
mins.push(minDiffInBST(root.right));
}
return Math.min(...mins)
};
const findMax = node => {
if(node.right) {
return findMax(node.right);
}
return node.val;
}
const findMin = node => {
if(node.left) {
return findMin(node.left);
}
return node.val;
}
执行用时 : 76 ms, 在所有 JavaScript 提交中击败了79.38%的用户
内存消耗 : 34.5 MB, 在所有 JavaScript 提交中击败了50.00%的用户