难度简单347
给你一个二叉搜索树的根节点 root
,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
示例 1:
输入:root = [4,2,6,1,3] 输出:1
示例 2:
输入:root = [1,0,48,null,null,12,49] 输出:1
提示:
- 树中节点的数目范围是
[2, 104]
0 <= Node.val <= 105
注意:本题与 783 力扣 相同
/**
* 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 {
List<Integer> list = new ArrayList<Integer>();
public int getMinimumDifference(TreeNode root) {
if(root == null) return Integer.MAX_VALUE;
getMinimumDifference(root.left);
list.add(root.val);
getMinimumDifference(root.right);
return handle();
}
int handle()
{
int min = Integer.MAX_VALUE;
for(int i=0;i<list.size()-1;i++)
{
min = Math.min(min,Math.abs(list.get(i)-list.get(i+1)));
}
return min;
}
}
/**
* 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 {
boolean flag = true;
int temp = 0;
int ans = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
//中序递归
if(root==null) return 0;
getMinimumDifference(root.left);
if(flag==true) temp = root.val;
else
{
int x = Math.abs(temp-root.val);
ans = ans<x?ans:x;
temp = root.val;
}
flag = false;
getMinimumDifference(root.right);
return ans;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69067.html