PS/LeetCode

LeetCode / Tree / 530번 / Minimum Absolute Difference in BST / JS

KimMinJun 2023. 6. 17. 13:55

< 문제 바로가기 >

 

Minimum Absolute Difference in BST - LeetCode

Can you solve this real interview question? Minimum Absolute Difference in BST - Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.   Example 1: [https://assets.l

leetcode.com

 

< 문제 간단설명 >

BST(Binary Search Tree)를 이루는 모든 노드들 중에서 2개의 노드를 뽑아 뺐을 때, 가장 작은 절댓값의 차이를 반환하는 문제이다.

 

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var getMinimumDifference = function (root) {
  let nodeList = [];

  // 전위 순회
  const traverse = (node) => {
    if (!node) {
      return null;
    }

    traverse(node.left);
    nodeList.push(node.val);
    traverse(node.right);
  };

  traverse(root);

  let min = Infinity;
  for (let i = 1; i < nodeList.length; i += 1) {
    let diff = nodeList[i] - nodeList[i - 1];
    min = Math.min(min, diff);
  }

  return min;
};