?LeetCode刷題實(shí)戰(zhàn)530:二叉搜索樹的最小絕對差
Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
示例? ? ? ? ? ? ? ? ? ? ? ? ?


解題
思路:利用二叉搜索樹-中序遍歷遞歸
class?Solution?{
????// 二叉搜索樹的最小絕對差
????int?min_diff = Integer.MAX_VALUE;
????int?pre = -1;
????public?int?getMinimumDifference(TreeNode root)?{
????????// 中序遍歷
????????if(root==null){
????????????return?min_diff;
????????}
????????// 左根右
????????getMinimumDifference(root.left);
????????if(pre!=-1){
????????????min_diff = Math.min(Math.abs(root.val-pre),min_diff);
????????????pre = root.val;
????????}else{
????????????pre = root.val;
????????}
????????getMinimumDifference(root.right);
????????return?min_diff;
????}
}
評論
圖片
表情
