zoukankan      html  css  js  c++  java
  • [LeetCode] 783. Minimum Distance Between BST Nodes


    Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.

    Example :

    Input: root = [4,2,6,1,3,null,null]
    Output: 1
    Explanation:
    Note that root is a TreeNode object, not an array.
    
    The given tree [4,2,6,1,3,null,null] is represented by the following diagram:
    
              4
            /   
          2      6
         /     
        1   3  
    
    while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.

    题意:给一个二叉搜索树,找到其中两个节点的最小差值
    二叉搜索树,左孩子小于根节点,右孩子大于根节点
    所以,二叉搜索树 有着中序有序的特点
    我们可以对其中序遍历,把数提出来,判断相邻两节点
    class Solution {
    private List<Integer> list;
        private void DFS(TreeNode root) {
            if (root.left != null)
                DFS(root.left);
            list.add(root.val);
            if (root.right != null)
                DFS(root.right);
        }
        public int minDiffInBST(TreeNode root) {
            list = new ArrayList<>();
            int min = 3276800;
            DFS(root);
            for (int i = 0; i < list.size() - 1; i++) {
                int temp = list.get(i+1) - list.get(i);
                min = Math.min(temp, min);
            }
            return min;
        }
    }
    
    
     

     当然这个算法显然有些多余,其一:额外开了O(n)的空间,其二多遍历了一遍

    既然知道是中序有序的,那我们可以直接在遍历的时候就判断

    class Solution {
        private int pre = -1;
        private int min = 3276800;
        public void DFS(TreeNode root) {
            if (root == null)
                return;
            DFS(root.left);
            if (pre != -1)
                min = Math.min(min, root.val - pre);
            pre = root.val;
            DFS(root.right);
        }
        
        public int minDiffInBST(TreeNode root) {
            DFS(root);
            return min;
        }
    }
  • 相关阅读:
    上班中午
    有些确实牛擦的有点嚣张!!! (zz)
    Docker学习笔记(二)
    结对项目第二阶段小结
    软件工程结课总结
    案例分析作业
    结对编程总结
    Docker学习笔记(一)
    四则运算
    构建之法1~5章
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9632661.html
Copyright © 2011-2022 走看看