前言
二叉树的特点(例图只是二叉树的一种情况,不要尝试用例图推理以下结论)
- 除了最下面一层,每个节点都是父节点,每个节点都有且最多有两个子节点;
- 除了嘴上面一层,每个节点是子节点,每个节点都会有一个父节点;
- 最上面一层的节点(即例图中的节点50)为根节点;
1 节点的javascript实现
1 2 3 4 5 6 7 8 9 10 11
| function Node(data, left, right) { this.data = data; this.left = left; this.right = right; this.show = show; }
function show() { return this.data; }
|
感受下上面实现节点的代码,感觉和链表有点相似不是吗,存着当前值,又存着下个节点(左、右子节点)的引用,下面是一张伪代码的草图:
2 二叉树的实现
实现二叉树,当然就是要插入节点构成二叉树,先看看实现二叉树的js代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| function BST() { this.root = null; this.insert = insert; }
function insert(data) { var n = new Node(data, null, null); if (this.root == null) { this.root = n; } else { var current = this.root; var parent; while (true) { parent = current; if (data < current.data) { current = current.left; if (current == null) { parent.left = n; break; } } else { current = current.right; if (current == null) { parent.right = n; break; } } } } }
|
然后是看一下伪代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| function BST() { this.root = null; this.insert = insert; }
function insert(data) { var n = new Node(data, null, null); if (该二叉树是否为空,是空则根节点为空,因此可以用根节点判断二叉树是否为空) { this.root = n; } else { var current = this.root; var parent; while (true) { parent = current; if (data < current.data) { current = current.left; if (current == null) { parent.left = n; break; }
if(current.left == null){ current.left = n; break; }else{ current = current.left; } } else { current = current.right; if (current == null) { parent.right = n; break; } } } } }
|
下面是一个更好理解的插入函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| function insert(data) { var n = new Node(data, null, null); if (this.root == null) { this.root = n; } else { var current = this.root; while (true) { if (data < current.data) { if (current.left == null) { current.left = n; break; }else{ current = current.left; } }else { if (current.right == null) { current.right = n; break; }else{ current = current.right; } } } } }
|
小结:
二叉树的实现的三个部件
- Node对象
1
| function Node(data, left, right) { ... }
|
- BST对象
- 插入节点函数
1
| function insert(data) { ... }
|