Um momento
Leetcode / 783. Minimum Distance Between BST Nodes

Pick a programming language:

Here is the source code for the solution to this problem.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDiffInBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode curr = root;
        TreeNode prev = null;
        int minDiff = 100000; // since 0 <= Node.val <= 10^5

        // iterative inorder traversal will go through nodes
        // in sorted order from smallest to largest.
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }
            else {
                curr = stack.pop();

                if (prev != null) {
                    minDiff = Math.min(minDiff, curr.val - prev.val);
                }

                prev = curr;
                curr = curr.right;
            }
        }

        return minDiff;
    }
}
Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: