Leetcode 783(530)二叉搜索树的最小距离

Leetcode 783(530)二叉搜索树的最小距离

数据结构定义:

给定一个二叉搜索树的根节点 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的差值。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

中序遍历:

class Solution {
    int min = Integer.MAX_VALUE;
    Integer preValue;
    public int minDiffInBST(TreeNode root) {
        if(root == null){
            return 0;
        }
        dfs(root);
        return min;
        
    }
    private void dfs(TreeNode root){
        if(min == 1){
            return;
        }
        if(root == null){
            return;
        }
        dfs(root.left);
        if(preValue != null){
            min = Math.min(min,Math.abs(root.val - preValue));
        }
        preValue = root.val;
        dfs(root.right);
    }
}

先排序后遍历:

class Solution {
    List<Integer> result = new ArrayList<>();
    public int minDiffInBST(TreeNode root) {
        dfs(root);
        if(result.size() <= 1) 
            return 0;
        int min = Integer.MAX_VALUE;
        for(int i = 1;i < result.size(); ++i){
            min = Math.min(min,Math.abs(result.get(i) -result.get(i - 1)));
        }
        return min;
    }
    private void dfs(TreeNode node){
        if(node == null)
            return;
        dfs(node.left);
        result.add(node.val);
        dfs(node.right);
    }
}
posted @ 2020-12-07 19:25  0xHigos  阅读(51)  评论(0编辑  收藏  举报