zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 530 二叉搜索树的最小绝对差(遍历树)

    530. 二叉搜索树的最小绝对差

    给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。

    示例:

    输入:

       1
        
         3
        /
       2
    

    输出:
    1

    解释:
    最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。

    PS:
    递归遍历

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        private int result = Integer.MAX_VALUE; private TreeNode preNode = null;
        public int getMinimumDifference(TreeNode root) {
        
        getMin(root);
        return result;
    }
    
    private void getMin(TreeNode root){
        if(root == null){
            return;
        }
        getMin(root.left);
        if(preNode != null)
        {
            result = Math.min(Math.abs(root.val - preNode.val), result);
        }
        preNode = root;
        getMin(root.right);
    }
    }
    
  • 相关阅读:
    rwkj 1337
    poj 1002
    map
    vector
    sort排序
    sort函数
    poj 2945
    poj2388
    rwkj 1422搜索(素数环)
    poj2503
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13074965.html
Copyright © 2011-2022 走看看