자바스크립트에서의 Nullish Coalescing을 이용한 트리 탐색 처리 방법

트리 구조는 많은 프로그래밍 문제에서 유용하게 사용되는 자료구조입니다. 이러한 트리 구조에서 특히 자식 노드의 존재 여부를 확인하고 처리하는 것은 중요한 작업입니다. 이때, Nullish Coalescing을 이용하면 효과적으로 트리 탐색을 처리할 수 있습니다.

Nullish Coalescing은 자바스크립트의 새로운 연산자로, 변수나 표현식이 null 또는 undefined인 경우 대체 값을 반환하는 역할을 합니다. 이를 이용하여 트리 탐색 시 자식 노드의 존재 여부를 간단하게 확인할 수 있습니다.

다음은 자바스크립트에서 Nullish Coalescing을 이용한 트리 탐색 처리 방법의 예시 코드입니다.

class TreeNode {
  constructor(value, left = null, right = null) {
    this.value = value;
    this.left = left;
    this.right = right;
  }
}

function searchTree(tree, target) {
  if (tree === null || tree === undefined) {
    return null;
  }

  if (tree.value === target) {
    return tree;
  }

  return searchTree(tree.left ?? null, target) ?? searchTree(tree.right ?? null, target);
}

// 트리 생성
const tree = new TreeNode(1,
  new TreeNode(2,
    new TreeNode(4),
    new TreeNode(5)),
  new TreeNode(3,
    new TreeNode(6),
    new TreeNode(7))
);

const targetNode = searchTree(tree, 5);
console.log(targetNode.value); // 출력: 5

위 예시 코드에서 searchTree 함수는 주어진 트리에서 주어진 타겟 값을 찾는 함수입니다. 트리를 순회하면서 자식 노드의 존재 여부를 Nullish Coalescing을 이용하여 확인하고, 타겟 값과 일치하는 노드를 반환합니다.

위 코드에서 ?? 연산자는 Nullish Coalescing 연산자로, 왼쪽 피연산자가 null 또는 undefined인 경우에만 오른쪽 피연산자를 반환합니다. 이를 이용하여 tree.left 또는 tree.right 값이 null 또는 undefined인 경우에는 각각 null을 전달하고, 그렇지 않은 경우에는 해당 자식 노드를 재귀적으로 탐색합니다.

트리 탐색 시 Nullish Coalescing을 이용하면 코드의 가독성과 간결성을 높일 수 있습니다. 또한, 자바스크립트에서 Nullish Coalescing은 null과 undefined를 명시적으로 다루는 습관을 갖게 해주어 버그를 예방하는 데도 도움이 됩니다.

#javascript #nullishcoalescing