JS-Tree: Binary tree in-order traversal



Preface

Recently, I summarized the tree algorithm and studied tree-related knowledge.


1. In-order traversal - recursion

1. Left, middle and right
2. The following input is: 4 2 5 1 6 3 7

  // 前序遍历
  const tree = {
    
    
    val: '1',
    left: {
    
    
      val: '2',
      left: {
    
     val: '4', left: null, right: null },
      right: {
    
     val: '5', left: null, right: null },
    },
    right: {
    
    
      val: '3',
      left: {
    
     val: '6', left: null, right: null },
      right: {
    
     val: '7', left: null, right: null },
    },
  }
	
  // 前序遍历
console.log(fun1(tree))

function fun1(root: any) {
    
    
  const arr: any[] = []
  const fun = (node: any) => {
    
    
    if (!node)
      return
    fun(node.left)
    arr.push(node.val)
    fun(node.right)
  }
  fun(root)
  return arr
}

2. In-order traversal-queue

1. Left, middle and right
2. The following input is: 4 2 5 1 6 3 7

function fun2(root: any) {
    
    
  const arr: any[] = []
  const stack = []
  let o = root
  while (stack.length || o) {
    
    
    while (o) {
    
    
      stack.push(o)
      o = o.left
    }
    const n = stack.pop()
    arr.push(n.val)
    o = n.right
  }
  return arr
}

Summarize

This is the in-order traversal of the binary tree of the tree. I hope it can help you!

Guess you like

Origin blog.csdn.net/smileKH/article/details/133742947