How to implement binary tree traversal using JavaScript
This article mainly introduces the method of implementing binary tree definition, traversal and search in JavaScript. It analyzes the related concepts of binary trees in detail in the form of examples and the common operating techniques of constructing binary trees, traversing and searching binary trees in JavaScript. Friends who need it can Refer to the following
The example of this article describes how to implement binary tree definition, traversal and search using JavaScript. Share it with everyone for your reference, the details are as follows:
binary tree
Before writing this article, let’s talk about the data structure and The algorithm series contains many things, such as sorting, linear tables, generalized tables, trees, and graphs. Everyone knows this, but how many of these things can we use in our work after we learn them? According to I know that most companies, first-line coders, losers, and programmers do not use these things. In this case, why should I emphasize this series? I think algorithms and data structures are the basic skills of programming. The premise is to break away from First-line coders and ordinary programmers are, to put it simply, to make themselves better. Secondly, languages are all understood. As long as you master one language, learning other languages is like going with the flow, without any effort. Another point is that I will keep writing this series. Although I searched a lot on the Internet and I have already finished it, I have two purposes for writing. The first is to share it with everyone, and the second is to make myself more in-depth. understand. Okay, not much else to say. I recently reviewed binary trees, so I will write this first, and then I will add sorting, linear tables, and generalized tables in sequence. . . . Wait
Binary tree
When it comes to binary trees, we will definitely ask, what is a binary tree, what is a binary tree, what is it used for, why do we Want to learn it? If you didn't ask yourself these questions when you were learning binary trees, then your understanding of it is only an understanding. Now let's talk about what a binary tree is. A binary tree is a data structure, and its organizational relationship is like a tree in nature. The official language definition is: It is a set of finite elements, which is either empty or consists of an element called the root and two disjoint binary trees called the left subtree and the right subtree respectively. As for why I should learn it, my mother always said, kid, you will understand when you grow up.
Properties of binary trees
Property 1: The number of nodes on the i-th level of a binary tree is at most 2i-1 (i≥1);
Property 2: Depth The binary tree for k has at most 2k-1 nodes (k≥1).
Property 3: In any binary tree, if the number of leaf nodes (that is, nodes with degree 0) is n0, the number of nodes with degree 1 is n1, and the number of nodes with degree 2 is n2, Then no=n2 1.
Storage structure and construction of binary trees
There are two ways to store binary trees, one is sequential storage, for example: var binaryTree = [' a', 'b', 'c', 'd', 'e', 'f', 'h', 'i'];
This is a binary tree, assuming binaryTree[i] is a binary tree node, then its left child node leftChild = binaryTree[i*2 1], then the corresponding right child node rightChild = binaryTree[i*2 2]; In general, this structure of sequential storage is less used, and the other The storage method is chain storage. Below I will use code to describe in detail the construction and storage method of the binary tree structure. There are two ways to build a binary tree. One is recursive construction, which is very simple, and the other is non-recursive construction. This type is a little more complicated than the previous one, but don't worry, I'll add detailed comments to the code and follow it step by step. We now use 26 English letters to build a binary tree
Copy code The code is as follows:
var charecters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P ', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
at Before building a binary tree, we will use a node object. The node object is as follows: (Note: I will put the object-oriented, prototype, and grammatical features of javascript in this series of javascript language knowledge points)
/* *二叉树的节点对象 */ function Node() { this.text = ''; //节点的文本 this.leftChild = null; //节点的左孩子引用 this.rightChild = null; //节点右孩子引用 }
Recursively build a binary tree
After building the binary tree node, we then use recursion to build the binary tree
var charecters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; function buildTree(node, i) { var leftIndex = 2*i+1, //左孩子节点的索引 rightIndex = 2*i+2; //右孩子节点的索引 if(leftIndex < charecters.length) { //判断索引的长度是否超过了charecters数组的大小 var childNode = new Node(); //创建一个新的节点对象 childNode.text = charecters[leftIndex]; //给节点赋值 node.leftChild = childNode; //给当前节点node加入左孩子节点 buildTree(childNode, leftIndex); //递归创建左孩子 } if(rightIndex < charecters.length) { //下面注释参照上面的构建左孩子的节点 var childNode = new Node(); childNode.text = charecters[rightIndex]; node.rightChild = childNode; buildTree(childNode, rightIndex); } } //下面构造二叉树 var node = new Node(); node.text = charecters[0]; buildTree(node, 0); //索引i是从0开始构建
Non-recursively build a binary tree
The following is a non-recursive way to construct a binary tree:
var root; function createBinaryTree() { var len = charecters.length, //数组的长度 index = 0, //索引从0开始 nodes = new Array(); //创建一个临时数组,用于存放二叉树节点 //循环创建二叉树节点存放到数组中 for (var i = 0 ; i < charecters.length ; i++) { var node = new Node(); node.text = charecters[i]; nodes.push(node); } //循环建立二叉树子节点的引用 while(index < len) { var leftIndex = 2*index+1, //当前节点左孩子索引 rightIndex = 2*index+2; //当前节点右孩子索引 //给当前节点添加左孩子 nodes[index].leftChild = nodes[leftIndex]; //给当前节点添加右孩子 nodes[index].rightChild = nodes[rightIndex]; index++; } root = nodes[0]; }
Three traversals of a binary tree
好了,现在我们已经成功构建了二叉树的链式结构,在构建了二叉树的链式结构后我们进入二叉树的最基本的遍历了,遍历有三种最基本的遍历,我不说想必大家都知道,先序遍历,中序遍历和后续遍历。虽然这三种遍历递归方式都比较简单,但非递归方式就不是那么容易了,当时我在实现的时候都卡了半天,真的是说起来容易做起来难啊,在实现遍历前我们首先要来实现的是栈,因为在非递归遍历的时候会用到栈,那到底什么是栈呢,这里我就简单介绍下吧,有兴趣的朋友可以去维基百科有权威的定义,栈和队列也是一种数据结构,栈存放数据的时候是先进先出,而队列是先进后出。
实现栈的对象
下面用javascript来实现栈的对象
function Stack() { var stack = new Array(); //存放栈的数组 //压栈 this.push = function(o) { stack.push(o); }; //出栈 this.pop = function() { var o = stack[stack.length-1]; stack.splice(stack.length-1, 1); return o; }; //检查栈是否为空 this.isEmpty = function() { if(stack.length <= 0) { return true; } else { return false; } }; } //使用方式如下 var stack = new Stack(); stack.push(1); //现在栈中有一个元素 stack.isEmpty(); //false , 栈不为空 alert(stack.pop()); //出栈, 打印1 stack.isEmpty(); //true, 此时栈为空,因为在调用了stack.pop()之后元素出栈了,所以为空
1. 先序遍历
在实现了栈对象以后我们首先来进行先序遍历的递归方式
function firstIteration(node) { if(node.leftChild) { //判断当前节点是否有左孩子 firstIteration(node.leftChild); //递归左孩子 } if(node.rightChild) { //判断当前节点是否有右孩子 firstIteration(node.rightChild); //递归右孩子 } } //递归遍历二叉树 firstIteration(root);
先序遍历的非递归方式
上面的代码大家可以在firstIteration()方法中加个alert()函数来验证是否正确。那么下面就要说说先序遍历的非递归方式,遍历思想是这样的:先访问根节点在访问左节点, 最后访问右节点。从根节点一直往下访问找左孩子节点,直到最后一个左孩子节点(将这条路径保存到栈中),然后再访问最后一个左孩子的兄弟节点(右孩子节点),之后回溯到上一层(将栈中的元素取出 就是出栈),又开始从该节点(回溯到上一层的节点)一直往下访问找左孩子节点... 直到栈中的元素为空,循环结束。
function notFirstIteration(node) { var stack = new Stack(), //开辟一个新的栈对象 resultText = ''; //存放非递归遍历之后的字母顺序 stack.push(root); //这个root在上面非递归方式构建二叉树的时候已经构建好的 var node = root; resultText += node.text; while(!stack.isEmpty()) { while(node.leftChild) { //判断当前节点是否有左孩子节点 node = node.leftChild; //取当前节点的左孩子节点 resultText += node.text; //访问当前节点 stack.push(node); //将当前节点压入栈中 } stack.pop(); //出栈 node = stack.pop().rightChild; //访问当前节点的兄弟节点(右孩子节点) if(node) { //当前节点的兄弟节点不为空 resultText += node.text; //访问当前节点 stack.push(node); //将当前节点压入栈中 } else { //当前节点的兄弟节点为空 node = stack.pop(); //在回溯到上一层 } } } //非递归先序遍历 notFirstIteration(root);
2. 中序遍历
只要把思路理清楚了现实起来其实还是挺容易的,只要我们熟悉了一种二叉树的非递归遍历方式,其他几种非递归方式就容易多了,照着葫芦画瓢,下面是中序遍历的递归方式,中序遍历的思想是:先访问左孩子节点,在访问根节点,最后访问右节点
var strText = ""; function secondIteration(node) { //访问左节点 if(node.leftChild) { if(node.leftChild.leftChild) { secondIteration(node.leftChild); } else { strText += node.leftChild.text; } } //访问根节点 strText += node.text; //访问右节点 if(node.rightChild) { if(node.rightChild.leftChild) { secondIteration(node.rightChild); } else { strText += node.rightChild.text; } } } secondIteration(root); alert(strText);
中序遍历的非递归方式
思想是:1. 从根节点一直往下找左孩子节点,直到找到最后一个左孩子节点(用栈将此路径保存,但不访问)2.访问最后一个左孩子节点,然后再访问根节点(要先弹出栈,就是在栈中取上一层节点)3.在访问当前节点(最后一个左孩子节点)的兄弟节点(右孩子节点),这里要注意如果兄弟节点是一个叶节点就直接访问,否则是兄弟节点是一颗子树的话不能马上访问,要先来重复 1, 2,3步骤, 直到栈为空,循环结束
function notSecondIteration() { var resultText = '', stack = new Stack(), node = root; stack.push(node); while(!stack.isEmpty()) { //从根节点一直往下找左孩子节点直到最后一个左孩子节点,然后保存在栈中 while(node.leftChild) { node = node.leftChild; stack.push(node); } //弹出栈 var tempNode = stack.pop(); //访问临时节点 resultText += tempNode.text; if(tempNode.rightChild) { node = tempNode.rightChild; stack.push(node); } } alert(resultText); }
3. 后续遍历
最后就还剩下一种遍历方式,二叉树的后续遍历,后续遍历的思想是:先访问左孩子节点,然后在访问右孩子节点,最后访问根节点
后续遍历的递归方式
var strText = ''; function lastIteration(node) { //首先访问左孩子节点 if(node.leftChild) { if(node.leftChild.leftChild) { lastIteration(node.leftChild); } else { strText += node.leftChild.text; } } //然后再访问右孩子节点 if(node.rightChild) { if(node.rightChild.rightChild) { lastIteration(node.rightChild); } else { strText += node.rightChild.text; } } //最后访问根节点 strText += node.text; } //中序递归遍历 lastIteration(root); alert(strText);
后续非递归遍历
后续非递归遍历的思想是:1.从根节点一直往下找左孩子节点,直到最后一个左孩子节点(将路径保存到栈中,但不访问)2.弹出栈访问最后一个左孩子节点 3.进入最后一个左孩子节点的兄弟节点,如果兄弟节点是叶节点就访问它,否则将该节点重复 1, 2步骤, 直到栈中的元素为空,循环结束。3.访问根节点
function notLastIteration() { var strText = '', stack = new Stack(); nodo = root; stack.push(node); while(!stack.isEmpty()) { while(node.leftChild) { node = node.leftChild; stack.push(node); } //弹出栈 var tempNode = stack.pop(); //访问左孩子节点 strText += tempNode.text; //访问右孩子节点 if(tempNode.rightChild) { if(tempNode.rightChild.leftChild || tempNode.rightChild.rightChild) { //判断最后一个左孩子节点的兄弟节点是否为页节点 stack.push(tempNode.rightChild); } else { strText += tempNode.rightChild.text; } } } alert(strText); }
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
在webpack中有关于jquery插件的环境配置(详细教程)
The above is the detailed content of How to implement binary tree traversal using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Hard drive serial numbers and MAC addresses are important identifiers in computer hardware and are very useful in managing and maintaining computer systems. This article will introduce how to find the hard disk serial number and MAC address. 1. Find the hard drive serial number. The hard drive serial number is a unique identifier used by the hard drive manufacturer to identify and track the hard drive. In different operating systems, the method of finding the hard drive serial number is slightly different. Windows: Open Command Prompt (search for "cmd" in the Start menu) and enter the following command and press Enter: wmicdisk

Apple's Find My app allows you to locate your iPhone or other device to prevent it from being lost or forgotten. While Find My is a useful tool for tracking devices, you may want to disable it if you're concerned about privacy issues, don't want to drain your battery, or for other reasons. Fortunately, there are several ways to turn off Find My on iPhone, all of which we will explain in this article. How to Turn off Find My on iPhone [4 Methods] You can turn off Find My on iPhone in four ways. If you used Method 1 to turn off Find, you can do this from the device you want to disable it on. To proceed with methods 2, 3, and 4, the iPhone that you want to turn off Find Finder should be powered off or

The composite primary key in MySQL refers to the primary key composed of multiple fields in the table, which is used to uniquely identify each record. Unlike a single primary key, a composite primary key is formed by combining the values of multiple fields. When creating a table, you can define a composite primary key by specifying multiple fields as primary keys. In order to demonstrate the definition and function of composite primary keys, we first create a table named users, which contains three fields: id, username and email, where id is an auto-incrementing primary key and user

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

Java is a popular programming language with powerful file handling capabilities. In Java, traversing a folder and getting all file names is a common operation, which can help us quickly locate and process files in a specific directory. This article will introduce how to implement a method of traversing a folder and getting all file names in Java, and provide specific code examples. 1. Use the recursive method to traverse the folder. We can use the recursive method to traverse the folder. The recursive method is a way of calling itself, which can effectively traverse the folder.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to PHP interface and how it is defined. PHP is an open source scripting language widely used in Web development. It is flexible, simple, and powerful. In PHP, an interface is a tool that defines common methods between multiple classes, achieving polymorphism and making code more flexible and reusable. This article will introduce the concept of PHP interfaces and how to define them, and provide specific code examples to demonstrate their usage. 1. PHP interface concept Interface plays an important role in object-oriented programming, defining the class application

How to Check the Serial Number of a Computer Hard Drive With the development of computer technology, computer hard drives have become an indispensable part of our lives. Whether it is storing important files or installing operating systems and software, you need to rely on the hard disk to complete it. Understanding some basic information about the computer hard drive, such as the hard drive's serial number, can help us better manage and maintain the computer system. So, how to check the serial number of a computer hard drive? This article will introduce several common methods. Method 1: Use the command line tool that comes with Windows system Windows system
