선주문 순회

2477 단어 javascriptleetcode
var preOrderTraversal = function (root) {
  // preOrder Traversal ->
  //  1. Visit current node
  //  2. Recursively traverse through the left subtree
  //  3. Recursively traverse through the right subtree

  // Initialize array of values
  let result = [];

  // Recursive function to traverse through subtrees
  travel(root, result);

  return result;
};

const travel = (node, result) => {
  if (node === null) {
    return null;
  }
  result.push(node.val); // Visit node
  travel(node.left, result); // Traverse through left subtree
  travel(node.right, result); // Traverse through right subtree
};


좋은 웹페이지 즐겨찾기