zoukankan      html  css  js  c++  java
  • LeetCode 783. 二叉搜索树节点最小距离

    二叉搜索树节点最小距离

    描述:

    给定一个二叉搜索树的根节点 root,返回树中任意两节点的差的最小值。

    示例:

    示例 1:

    输入:[3,4,5,1,2]
    输出:1
    

    示例 2:

    输入:[2,2,2,0,1]
    输出:0

    题解:

    一、排序【通过】

    class Solution {
        List<Integer> vals;
        public int minDiffInBST(TreeNode root) {
            vals = new ArrayList();
            dfs(root);
            Collections.sort(vals);
    
            int ans = Integer.MAX_VALUE;
            for (int i = 0; i < vals.size() - 1; ++i)
                ans = Math.min(ans, vals.get(i+1) - vals.get(i));
    
            return ans;
        }
    
        public void dfs(TreeNode node) {
            if (node == null) return;
            vals.add(node.val);
            dfs(node.left);
            dfs(node.right);
        }
    }

    二、中序遍历【通过】

    class Solution {
        Integer prev, ans;
        public int minDiffInBST(TreeNode root) {
            prev = null;
            ans = Integer.MAX_VALUE;
            dfs(root);
            return ans;
        }
    
        public void dfs(TreeNode node) {
            if (node == null) return;
            dfs(node.left);
            if (prev != null)
                ans = Math.min(ans, node.val - prev);
            prev = node.val;
            dfs(node.right);
        }
    }
    呵呵
  • 相关阅读:
    WEB API&API
    event flow
    JS-for的衍生对象
    JS-function
    Object Constructor
    前端发展史
    JavaScript中document.getElementById和document.write
    正则表达式把Paul换成Ringo
    11th blog
    10th week blog
  • 原文地址:https://www.cnblogs.com/jiazhiyuan/p/13363126.html
Copyright © 2011-2022 走看看