1、普通方法
function binaryTree() {
// 定义node节点
var Node = function(key) {
this.key = key;
this.left = left;
this.right = right
}
// 当前根节点
var root = null
// 插入元素函数
var insert = function(value){
// 初始化新节点
var newNode = new Node(value)
// 如果没有根节点,则将新节点赋值给根
if(this.root === null) {
this.root = newNode
} else {
// 存在根节点,就开始判断插入新节点
insertNode(root,newNode)
}
}
// 插入节点辅助函数
var insertNode = function(root,node) {
// 如果当前要插入节点的值小于当前节点的值,则要插入左节点,否则插入右节点
if(node.key < root.key) {
// 如果当前根节点左节点为空,则将要插入的节点插入当前根节点的左节点,否则递归当前根节点的左节点与要插入的节点
if(root.left === null) {
root.left = node
} else {
insertNode(root.left,node)
}
} else {
// 如果当前根节点右节点为空,则将要插入的节点插入当前根节点的右节点,否则递归当前根节点的右节点与要插入的节点
if(root.right === null) {
root.right = node
} else {
insertNode(root.right,node)
}
}
}
}
2、使用es6 类方法
class node {
constructor(val) {
this.key = val
this.left = null
this.right = null
}
}
class binaryTree() {
constructor() {
this.root = null
}
insert(val) {
let newNode = new node(val)
if(this.root === null) {
this.root = newNode
} else {
this.insertNode(this.root,newNode)
}
}
insertNode(root,curNode) {
if(root.key > curNode.key) {
if(root.left === null) {
root.left = curNode
} else {
this.insertNode(root.left,curNode)
}
} else {
if(root.right === null) {
root.right = curNode
} else {
this.insertNode(root.right,curNode)
}
}
}
}
3、遍历方法
3.1先序遍历
所谓的前序遍历就是先访问根节点,再访问左节点,最后访问右节点,
如上图所示,前序遍历结果为:ABDFECGHI
实现代码如下:
/**
* 二叉树前序遍历 根-> 左-> 右
* @param node 二叉树节点
*/
preOrderTraveral(node){
if(node == null){
return;
}
console.log(node.key);
preOrderTraveral(node.left);
preOrderTraveral(node.right);
}
3.2中序遍历
中序遍历就是先访问左节点,再访问根节点,最后访问右节点
如上图所示,中序遍历结果为:DBEFAGHCI
/**
* 二叉树中序遍历 左-> 根-> 右
* @param node 二叉树节点
*/
inOrderTraveral(node){
if(node == null){
return;
}
inOrderTraveral(node.left);
console.log(node.key);
inOrderTraveral(node.right);
}
3.2后序遍历
后序遍历就是先访问左节点,再访问右节点,最后访问根节点。
如上图所示,后序遍历结果为:DEFBHGICA
代码实现如下
/**
* 二叉树后序遍历 左-> 右-> 根
* @param node 二叉树节点
*/
postOrderTraveral(node){
if(node == null){
return;
}
postOrderTraveral(node.left);
postOrderTraveral(node.right);
console.log(node.key);
}