1. 程式人生 > >JS 實現二叉樹

JS 實現二叉樹

之前在網上學習了二叉排序樹的實現方法,然後想實現二叉樹,發現JS的實現不好找,就在二叉排序樹實現的基礎上改了一下,小白一名歡迎指教。
  • 二叉樹實現

在這裡插入圖片描述

var BinaryTree = function (key) {
	var tNode = function (key){
		this.key = key
		this.left = null
		this.right = null
	}
	var root = null,arr = []
	var insertNode = function (newNode) {
		if (arr[0].left == null) {
			arr[0].left = newNode
		} else if (arr[0].right == null) {
			arr[0].right = newNode
			arr.shift()
		}
		arr.push(newNode)
	}
	this.insert = function (key) {
		var newNode = new tNode(key)
		if (root == null) {
			root = newNode
			arr.push(root)
		} else {
			insertNode(newNode)
		}
	}
}
var nodes = [1,2,3,4,5,6,7,8]
var binaryTree = new BinaryTree()
nodes.forEach((key) => {
	binaryTree.insert(key)
})
  • 二叉排序樹
var BinaryTree = function (key) {
	var tNode = function (key){
		this.key = key
		this.left = null
		this.right = null
	}
	var root = null
	var insertNode = function (node, newNode) {
		if (newNode.key < node.key) {
			if (node.left == null) {
				node.left = newNode
			} else {
				insertNode(node.left, newNode)
			}
		} else {
			if (node.right == null) {
				node.right = newNode
			} else {
				insertNode(node.right, newNode)
			}
		}
	}
	this.insert = function (key) {
		var newNode = new tNode(key)
		if (root == null) {
			root = newNode
		} else {
			insertNode(root, newNode)
		}
	}
}
var nodes = [8,3,10,1,6,14,4,7,13]
var binaryTree = new BinaryTree()
nodes.forEach((key) => {
	binaryTree.insert(key)
})