javascript 遍历预购BST

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 遍历预购BST相关的知识,希望对你有一定的参考价值。

/* input: [2,3,4,5,2,3,4]
          2
        /   \
       3     4
      / \   / \
     5   2 3   4
*/
const input = {
  val: 2,
  right: {
     val: 4,
     right: { val: 4, right: null, left: null },
     left: { val: 3, right: null, left: null }
  },
  left: {
     val: 3,
     right: { val: 2, right: null, left: null },
     left: { val: 5, right: null, left: null }
  }
};

/**
 * Pre-order BST Traversal (Root->Left->Right). Recursive solution.
 * @param {TreeNode} root
 * @param {number[]} acc
 * @return {number[]}
 */
const preorderTraversalRecursive = (root, acc = []) => {
  if (!!root) {  
    acc.push(root.val);
    if (root.left) preorderTraversal(root.left, acc);
    if (root.right) preorderTraversal(root.right, acc);
  }
  return acc;
};

/**
 * Pre-order BST Traversal (Root->Left->Right). Iterative solution.
 * @param {TreeNode} root
 * @return {number[]}
 */
const preorderTraversalIterative = (root) => {
  /**
   * Algorithm:
   * 1. Create an empty stack [];
   * 2. Do while stack is not empty:
   * 2.1. Pop an item from stack and add it to result array.
   * 2.2. Push 'right child' of popped item to stack.
   * 2.3. Push 'left child' of popped item to stack.
   */
  if (root == null) {
    return [];
  }
  
  const stack = [];
  const result = [];
  
  stack.push(root);

  while(stack.length > 0) {
    let current = stack.pop();
    result.push(current.val);
    
    if (current.right) stack.push(current.right);
    if (current.left) stack.push(current.left);
  }
  
  return result;
};

以上是关于javascript 遍历预购BST的主要内容,如果未能解决你的问题,请参考以下文章

javascript 遍历有序BST

javascript实现BST

树--05---二叉树--02---二叉搜索树(BST)遍历

树的总结(遍历,BST,AVL原型,练习题)

c_cpp BST实施和遍历

06-二分搜索树 BST