Binary tree and its traversal method!

binary tree

What is a binary tree?

Each node in the tree can only have at most two child nodes. In JavaScript, Object is generally used to simulate a binary tree.

common operation

  • preorder traversal
  • Inorder traversal
  • post order traversal

preorder traversal

root or so.

Mantra:

  1. visit the root node
  2. Preorder traversal of the left subtree of the root node
  3. Preorder traversal of the right subtree of the root node
    insert image description here

Implemented recursively

function preorder(root) {
    
    
    if (!root) return

    console.log(root.val)
    preorder(root.left)
    preorder(root.right)
}

Implemented iteratively

function preorder(root) {
    
    
    if (!root) return

    const stack = [root]

    while (stack.length) {
    
    
        const n = stack.pop()

        console.log(n)
        if (n.right) stack.push(n.right)
        if (n.left) stack.push(n.left)
    }
}

Inorder traversal

Left and right.

Mantra:

  1. Inorder traversal of the left subtree of the root node
  2. visit the root node
  3. Inorder traversal of the right subtree of the root node

insert image description here

Implemented recursively

function inorder(root) {
    
    
    if (!root) return

    inorder(root.left)
    console.log(root.val)
    inorder(root.right)
}

Implemented iteratively

function inorder(root) {
    
    
    if (!root) return

    const stack = [root]

    while (stack.length) {
    
    
        const n = stack.pop()

        console.log(n)
        if (n.right) stack.push(n.right)
        if (n.left) stack.push(n.left)
    }
}

post order traversal

left and right roots.

Mantra:

  1. Post-order traversal of the left subtree of the root node
  2. Post-order traversal of the right subtree of the root node
  3. visit the root node

insert image description here

Implemented recursively

function postorder(root) {
    
    
    if (!root) return

    postorder(root.left)
    postorder(root.right)
    console.log(root.val)
}

Implemented iteratively

function postorder(root) {
    
    
    if (!root) return

    const outputStack = []
    const stack = [root]

    while (stack.length) {
    
    
        const n = stack.pop()

        outputStack.push(n)
        if (n.left) stack.push(n.left)
        if (n.right) stack.push(n.right)
    }

    while (outputStack.length) {
    
    
        const n = outputStack.pop()
        console.log(n.val)
    }
}

Original Link: Vegetable Garden Front End

Guess you like

Origin blog.csdn.net/qq2603375880/article/details/131436839