zoukankan      html  css  js  c++  java
  • 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);
        }
    }
    
  • 相关阅读:
    css3 box-shadow
    JS的Document属性和方法
    简单配色方案web
    ps中参考线的使用技巧
    min-width() ie6
    js 模拟右键菜单
    display:table-cell
    js opener 的使用
    js的 new image()
    CSS 中文字体 Unicode 编码方案
  • 原文地址:https://www.cnblogs.com/CodingXu-jie/p/14098950.html
Copyright © 2011-2022 走看看