[js Binary Algorithm]

1. Create a binary tree node class

First, you need to define a node class, including attributes such as node value, left child node, and right child node. A simple implementation is as follows:

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

2. Create a binary tree

Next, you need to create a binary tree class to implement operations such as insertion and traversal of the binary tree. The insertion method needs to judge the size relationship between the current node value and the inserted value, and choose to insert to the left or right subtree.

class BinaryTree {
    
    
  constructor() {
    
    
    this.root = null;
  }
  
  insert(val) {
    
    
    const newNode = new TreeNode(val);
    if (!this.root) {
    
    
      this.root = newNode;
      return;
    }
    let current = this.root;
    while (current) {
    
    
      if (val < current.val) {
    
    
        if (current.left) {
    
    
          current = current.left;
        } else {
    
    
          current.left = newNode;
          break;
        }
      } else {
    
    
        if (current.right) {
    
    
          current = current.right;
        } else {
    
    
          current.right = newNode;
          break;
        }
      }
    }
  }
  
  // 前序遍历
  preOrderTraversal(node = this.root, result = []) {
    
    
    if (node) {
    
    
      result.push(node.val);
      this.preOrderTraversal(node.left, result);
      this.preOrderTraversal(node.right, result);
    }
    return result;
  }
  
  // 中序遍历
  inOrderTraversal(node = this.root, result = []) {
    
    
    if (node) {
    
    
      this.inOrderTraversal(node.left, result);
      result.push(node.val);
      this.inOrderTraversal(node.right, result);
    }
    return result;
  }
  
  // 后序遍历
  postOrderTraversal(node = this.root, result = []) {
    
    
    if (node) {
    
    
      this.postOrderTraversal(node.left, result);
      this.postOrderTraversal(node.right, result);
      result.push(node.val);
    }
    return result;
  }
}

3. Test code

Finally, you can write some test code to verify the correctness of the implementation, for example:

const binaryTree = new BinaryTree();
binaryTree.insert(8);
binaryTree.insert(3);
binaryTree.insert(10);
binaryTree.insert(1);
binaryTree.insert(6);
binaryTree.insert(14);

console.log(binaryTree.preOrderTraversal());  // [8, 3, 1, 6, 10, 14]
console.log(binaryTree.inOrderTraversal());   // [1, 3, 6, 8, 10, 14]
console.log(binaryTree.postOrderTraversal()); // [1, 6, 3, 14, 10, 8]

Here, preorder, inorder and postorder traversal are tested as examples, and the results meet expectations.

Guess you like

Origin blog.csdn.net/Ge_Daye/article/details/132187717