Details about binary tree traversal in JS, and details about the js Binary Tree calendar

Source: Internet
Author: User

Details about binary tree traversal in JS, and details about the js Binary Tree calendar

A binary tree consists of a root node, a left subtree, and a right subtree. The left subtree and a friend subtree are a binary tree respectively.
This article mainly implements binary tree traversal in JS.

Example of a binary tree

var tree = { value: 1, left: {  value: 2,  left: {   value: 4  } }, right: {  value: 3,  left: {   value: 5,   left: {    value: 7   },   right: {    value: 8   }  },  right: {   value: 6  } }}

Breadth-first Traversal
Breadth-first traversal starts from the first layer (root node) of a binary tree and goes from top to bottom layer. In the same layer, nodes are accessed one by one from left to right.
Implementation:
<! -- More -->
Use arrays to simulate queues. First, add the root node to the queue. When the queue is not empty, execute a loop: Fetch a node in the queue. If the left subtree of the node is not empty, the left subtree of the node is entered into the queue; if the right subtree of the node is not empty, the right subtree of the node is put into the queue.
(The description is a bit unclear. Check the Code directly .)

var levelOrderTraversal = function(node) {  if(!node) {    throw new Error('Empty Tree') }  var que = [] que.push(node)  while(que.length !== 0) {  node = que.shift()    console.log(node.value)    if(node.left) que.push(node.left)    if(node.right) que.push(node.right) }}

Recursive Traversal
I think the three methods to express recursive traversal with these letters are good:
D: access the root node. L: traverse the left subtree of the root node. R: traverse the right subtree of the root node.
Sequential traversal: DLR
In-order traversal: LDR
Post-order traversal: LRD

The order of traversal follows the letter's meaning ^

These three types of traversal belong to recursive traversal, or Depth-First Search, DFS, because the total
Is to give priority to deep access.

Recursive Algorithms for sequential traversal:

var preOrder = function (node) {  if (node) {    console.log(node.value);  preOrder(node.left);  preOrder(node.right); }}

Recursive Algorithms for sequential traversal:

var inOrder = function (node) {  if (node) {  inOrder(node.left);    console.log(node.value);  inOrder(node.right); }}

Recursive Algorithms for post-order traversal:

var postOrder = function (node) {  if (node) {  postOrder(node.left);  postOrder(node.right);    console.log(node.value); }}

Non-recursive depth-first Traversal
In fact, I don't know who these concepts belong. In some books, the traversal of Binary Trees only describes the above three types of recursive traversal. Some are divided into two types: breadth-first traversal and depth-first traversal. Recursive traversal is divided into deep traversal. Some are divided into recursive traversal and non-recursive traversal, non-recursive traversal includes the breadth-first traversal and the following traversal. I personally think it is not important to know how to score points. It is good to know the methods and usage :)

The queue is used in the breadth-first traversal. Correspondingly, stack is used in this non-recursive depth-first traversal. In JS, we still use an array to simulate it.
Here we only talk about the first order:
Well, I tried to describe this algorithm, but I cannot clearly describe it. You will understand it by following the code.

var preOrderUnRecur = function(node) {  if(!node) {    throw new Error('Empty Tree') }  var stack = [] stack.push(node)  while(stack.length !== 0) {  node = stack.pop()    console.log(node.value)    if(node.right) stack.push(node.right)    if(node.left) stack.push(node.left) }}

After reading this article, I found the non-recursive post-order algorithm, so here I want to complete the non-recursive Traversal method.
Non-recursive Middle Order
Push the left node of the number to the stack, then extract the node, and then push the right node.

var inOrderUnRecur = function(node) {  if(!node) {    throw new Error('Empty Tree') }  var stack = []  while(stack.length !== 0 || node) {    if(node) {   stack.push(node)   node = node.left  } else {   node = stack.pop()      console.log(node.value)   node = node.right  } }}

Non-recursive post-order (using a stack)
Here, a temporary variable is used to record the last node into/out of the stack. The idea is to first push the root node and left tree into the stack, then extract the left tree, then push it into the right tree, and finally get the heel node.

var posOrderUnRecur = function(node) {  if(!node) {    throw new Error('Empty Tree') }  var stack = [] stack.push(node)  var tmp = null while(stack.length !== 0) {  tmp = stack[stack.length - 1]    if(tmp.left && node !== tmp.left && node !== tmp.right) {   stack.push(tmp.left)  } else if(tmp.right && node !== tmp.right) {   stack.push(tmp.right)  } else {      console.log(stack.pop().value)   node = tmp  } }}

Non-recursive back-order (using two stacks)
The idea of this algorithm is similar to that above. s1 is a bit like a temporary variable.

var posOrderUnRecur = function(node) {  if(node) {    var s1 = []    var s2 = []  s1.push(node)    while(s1.length !== 0) {   node = s1.pop()   s2.push(node)      if(node.left) {    s1.push(node.left)   }      if(node.right) {    s1.push(node.right)   }  }    while(s2.length !== 0) {      console.log(s2.pop().value);  } }}

Morris Traversal
This method does not require recursion or stack to implement three types of deep traversal. The space complexity is O (1) (I am not particularly aware of this concept org)
(I put these three algorithms first, and I will study them when I have time)
Morris preface:

var morrisPre = function(head) {  if(!head) {    return }  var cur1 = head,   cur2 = null while(cur1) {  cur2 = cur1.left    if(cur2) {      while(cur2.right && cur2.right != cur1) {    cur2 = cur2.right   }      if(!cur2.right) {    cur2.right = cur1        console.log(cur1.value)    cur1 = cur1.left        continue   } else {    cur2.right = null   }  } else {       console.log(cur1.value)  }  cur1 = cur1.right }}

Morris Middle Order:

var morrisIn = function(head) {  if(!head) {    return }  var cur1 = head,   cur2 = null while(cur1) {  cur2 = cur1.left    if(cur2) {      while(cur2.right && cur2.right !== cur1) {    cur2 = cur2.right   }      if(!cur2.right) {    cur2.right = cur1    cur1 = cur1.left        continue   } else {    cur2.right = null   }  }    console.log(cur1.value)  cur1 = cur1.right }}

Post-Morris order:

var morrisPost = function(head) {  if(!head) {    return }  var cur1 = head,   cur2 = null while(cur1) {  cur2 = cur1.left    if(cur2) {      while(cur2.right && cur2.right !== cur1) {    cur2 = cur2.right   }      if(!cur2.right) {    cur2.right = cur1    cur1 = cur1.left        continue   } else {    cur2.right = null    printEdge(cur1.left)   }  }  cur1 = cur1.right } printEdge(head)}var printEdge = function(head) { 

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • Js array looping all elements in the array
  • How to Implement the for traversal in foreach in js
  • How to traverse JSON data in a JS Loop
  • JS array traversal mode for loop and for... in
  • JQuery $. each traverses JavaScript Array object instances
  • JS uses the for loop to traverse the child node to find elements
  • JQuery traverses the json array in three ways
  • Binary Tree explanation of JavaScript data structures and algorithms
  • Nodejs traverses the folder and counts the file size.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.