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 }
  }
};


/**
 * In-order BST Traversal (Root, Left, Right). Recursive solution.
 * @param {TreeNode} root
 * @param {number[]} acc
 * @return {number[]}
 */
var inorderTraversal = function(root, acc = []) {
    if (!!root) {
        if (root.left) inorderTraversal(root.left, acc);
        
        acc.push(root.val);
        
        if (root.right) inorderTraversal(root.right, acc);
    }

    return acc;
};

/**
 * In-order BST Traversal (Root, Left, Right). Iterative solution.
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
    /**
    * 1. Create an empty stack S.
    * 2. Initialize current node as root
    * 3. Push the current node to S and set current = current->left until current is NULL
    * 4. If current is NULL and stack is not empty then 
    * 4.1. Pop the top item from stack.
    * 4.2. Print the popped item, set current = popped_item->right 
    * 4.3. Go to step 3.
    * 5. If current is NULL and stack is empty then we are done.
    */
    if (root == null) {
        return [];
    }
    
    const stack = [];
    const result = [];
    
    let isDone = false; 
    let current = root;
    
    while (!isDone) {
        if (current) {   
            stack.push(current);
            current = current.left;
        } else {
            if (stack.length) {
                let currentPopped = stack.pop();
                result.push(currentPopped.val);
                current = currentPopped.right;
            } else {
                isDone = true
            }
        }       
    }
    
    return result;
}

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

leetcode 783. Minimum Distance Between BST Nodes ---中序遍历

二叉搜索树BST

二叉排序树(BST)

javascript实现BST

刷题日记Day5 | BST(增删改查)

刷题日记Day4 | BST