题目描述:
给你一个二叉搜索树的根节点 root ,返回树中任意两不同节点值之间的最小差值 。
输入:root = [4,2,6,1,3]
输出:1
输入:root = [1,0,48,null,null,12,49]
输出:1
提示:
- 树中节点数目在范围 [2, 100] 内
- 0 <= Node.val <= 10^5
题目分析:
其实一开始我是想过双重循环比较每一个元素和其他元素的差值的, 但是发现题目给的参数是一个头结点,而不是数组…(别骂了,别骂了,给笨比留点面子吧 T T).
正解是我们需要根据给定的BST根节点求出BST中序遍历的数组(升序数组), 任意两点之间最小差值即为相邻两点之间最小差值.
笨比实现:
(看完大佬中序遍历思路后自己实现)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDiffInBST(TreeNode root) {
ArrayList<TreeNode> list = new ArrayList<>();
inOrderTraversal(root, list);
int min = Math.abs(list.get(0).val - list.get(1).val);
for (int i = 1; i < list.size() - 1; i++) {
int temp = list.get(i + 1).val - list.get(i).val;
min = Math.min(min, temp);
}
return min;
}
private void inOrderTraversal(TreeNode root, ArrayList<TreeNode> list) {
if (root == null) {
return;
}
inOrderTraversal(root.left, list);
list.add(root);
inOrderTraversal(root.right, list);
}
}
如果有会分析时间空间复杂度的大佬可以评论下…我实在是分析不明白…
时间复杂度: 遍历了整个数据的长度 至少是O(n), 我感觉下面的中序遍历应该也有复杂度…但是我不会…
空间复杂度: 额外创建了一个存储所有元素的List,至少是O(n), 别的暂时没发现, 如果有错误欢迎大家指正.(别骂了, 别骂了 我是笨比还不行么 T T).
JAVA实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int result = 100001;
private int pre = -1;
public int minDiffInBST(TreeNode root) {
inOrderTraversal(root);
return result;
}
public void inOrderTraversal(TreeNode root) {
if (root == null) {
return;
}
inOrderTraversal(root.left);
if (pre != -1) {
result = Math.min(root.val - pre, result);
}
pre = root.val;
inOrderTraversal(root.right);
}
}
崇拜大佬思想的第四天…