二叉树是什么?
二叉树就是是指树中节点的度不大于2的有序树,它是一种最简单且最重要的树。 二叉树的递归定义为:二叉树是一棵空树,或者是一棵由一个根节点和两棵互不相交的,分别称作根的左子树和右子树组成的非空树;左子树和右子树又同样都是二叉树 。
二叉树的概念
- 根节点
- 右子树
- 左子树
二叉树的实现
```javascript // 创建节点 class CreateNode { constructor(key){
} }this.key = key;this.left = null;this.right = null;
class Tree { constructor() { // 创建根节点 this.root = null; } set(val){ // 创建节点 let node = new CreateNode(val); // 如果根节点为空,那么要插入的节点则作为根节点 if(!this.root){ this.root = node; }else{ // 如果根节点不为空,则正常插入节点 // 当前插入的节点 | 插入节点的位置 this.addNode(node,this.root); } } addNode(node,root){ // 判断节点插入的位置 // 如果插入的节点小于上面的节点则插入到左子树 if(node.key < root.key){ // 如果要插入的节点的左子树为空,直接插入,否则往下找 if(!root.left) { root.left = node; }else{ this.addNode(node,root.left); } }
// 如果插入的字节点大于插入当前位置的节点,那么则插在右面if(node.key > root.key){if(!root.right){root.right = node;}else{this.addNode(node,root.right)}}// 返回结果return this.root;}// 显示方法show(obj){// for(let key in obj){// if(typeof obj[key] == 'object'){// console.log(obj[key]);// this.show(obj[key])// }else{// console.log(obj[key]);// }// }console.log(this.root);}
}
<a name="LjjlA"></a>#### 二叉树的求最值```javascriptmax(){// 如果根节点不存在if(!this.root) return false;while(this.root.right){this.root = this.root.right;}// 返回结果return this.root;}
二叉树三种顺序图示
二叉树的先序
图示
二叉树先序的代码展示
class CreateNode {constructor(key) {this.key = key;this.left = null;this.right = null;}}class BinarySearchTree {constructor() {// 创建根节点this.root = null;}set(arr) {// 创建节点arr.forEach(item => {let node = new CreateNode(item);// 如果根节点为空,那么要插入的节点则作为根节点if (!this.root) {this.root = node;} else {// 如果根节点不为空,则正常插入节点// 当前插入的节点 | 插入节点的位置this.addNode(node, this.root);}})}addNode(node, root) {// 判断节点插入的位置// 如果插入的节点小于上面的节点则插入到左子树if (node.key < root.key) {// 如果要插入的节点的左子树为空,直接插入,否则往下找if (!root.left) {root.left = node;} else {this.addNode(node, root.left);}}// 如果插入的字节点大于插入当前位置的节点,那么则插在右面if (node.key > root.key) {if (!root.right) {root.right = node;} else {this.addNode(node, root.right)}}// 返回结果return this.root;}// 先序遍历 先遍历根节点,然后先从左子树遍历,左子树遍历完在遍历右子树prevTraval(callback) {this.prevTravalNode(this.root, callback)}prevTravalNode(node, callback) {// 如果节点存在,则打印该节点if (node) {// 调用回调callback(node.key);this.prevTravalNode(node.left, callback);this.prevTravalNode(node.right, callback)}}}var BST = new BinarySearchTree();BST.set([12, 18, 32, 4, 6,20, 45])BST.prevTraval((val) => console.log(val))
