当前位置:网站首页>Minimum absolute difference of binary search tree (use medium order traversal as an ordered array)

Minimum absolute difference of binary search tree (use medium order traversal as an ordered array)

2022-07-07 08:04:00 Hydrion-Qlz

530. The minimum absolute difference of binary search tree

The difficulty is simple

Give you a binary search tree root node root , return The minimum difference between the values of any two different nodes in the tree .

The difference is a positive number , Its value is equal to the absolute value of the difference between the two values .

Ideas

The problem needs to find the minimum of the absolute value of the difference between any two nodes on the binary search tree .

Notice the binary search tree , Binary search trees are ordered !

Traverse the binary search tree , What you get is actually an ordered array , Find the minimum difference on an ordered array , Is it very simple ?

package cn.edu.xjtu.carlWay.tree.minAbsoluteDifferenceInBST;

import cn.edu.xjtu.Util.TreeNode.TreeNode;

/** * 530.  The minimum absolute difference of binary search tree  *  Give you a binary search tree root node  root , return   The minimum difference between the values of any two different nodes in the tree  . * <p> *  The difference is a positive number , Its value is equal to the absolute value of the difference between the two values . * <p> * https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/ */
public class Solution {
    
    int result = Integer.MAX_VALUE;
    TreeNode pre = null;

    /** *  If you think of it as a mid order traversal, it is an ordered array  * * @param root * @return */
    public int getMinimumDifference(TreeNode root) {
    
        if (root == null) return 0;
        traversal(root);
        return result;
    }

    private void traversal(TreeNode root) {
    
        if (root == null) {
    
            return;
        }
        //  Traverse left subtree 
        traversal(root.left);
        
        //  Data processing in the middle 
        if (pre != null) {
    
            result = Math.min(result, root.val - pre.val);
        }
        pre = root;
        
        //  Traversal right subtree 
        traversal(root.right);
    }
}
原网站

版权声明
本文为[Hydrion-Qlz]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130645266464.html