给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
示例 1:
输入:root = [4,2,6,1,3]输出:1
解题思路:递归yyds,深度优先算法,先遍历左子树,再遍历右子树
/**
* 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 {
int min = Integer.MAX_VALUE;
TreeNode pre = null;
public void minT(TreeNode root) {
if(root == null ) {
return ;
}
minT(root.left);//先遍历左子树
if(pre != null) {
min = Math.min(root.val-pre.val, min);
}
pre = root;
minT(root.right);//再遍历右子树
}
public int minDiffInBST(TreeNode root) {
minT(root);
return min;
}
}
网友评论