创建二叉树
观察上面的图我们可以知道,二叉树实际就是一个递归的过程,不断的左子树、右子树,直到该节点没有左子树或者右子树。递归需要一个临界点来结束递归,不然会死循环,从图中可以知道树终止递归其实就是没有左子树、右子树,也就是叶子节点,所以我们需要把叶子节点补上,用 # 来表示 如:
1 const arr = ['A','B','D','#','#','E','#','#','C','F','#', '#', 'G', '#', '#']
步骤:
- 先创建跟节点
- 递归创建左子树
- 递归创建右子树
先序遍历构建
1 /* 2 * @Description: 3 * @Version: 1.0 4 * @Autor: longbs 5 * 先序构建 6 */ 7 8 class Node { 9 constructor (data = '#') { 10 this.data = data 11 this.lNode = null 12 this.rNode = null 13 } 14 } 15 16 class BiTree { 17 root = null 18 nodeList = [] 19 constructor (nodeList) { 20 this.root = new Node() 21 this.nodeList = nodeList 22 } 23 createNode (node) { 24 const data = this.nodeList.shift() 25 if (data === '#') return 26 node.data = data 27 // 下一个元素是不是空节点, 如果不是创建左节点 28 if (this.nodeList[0] !== '#') { 29 node.lNode = new Node(data) 30 } 31 this.createNode(node.lNode) 32 33 // 下一个元素是不是空节点, 如果不是创建右节点 34 if (this.nodeList[0] !== '#') { 35 node.rNode = new Node(data) 36 } 37 this.createNode(node.rNode) 38 39 } 40 } 41 42 const arr = ['A','B','D','#','#','E','#','#','C','F','#', '#', 'G', '#', '#'] 43 const bi = new BiTree(arr) 44 bi.createNode(bi.root) 45 console.log(bi.root)
层级遍历构建
还可以一层一层的来构建,如先创建跟节点,在创建下一层的左子树、右子树,在继续创建左子树的下一层(左右子树)。
步骤:
- 先创建跟节点
- 创建左子树
- 创建右子树
- 重复2、3过程
通常这种层次的问题可以使用队列来解决,先将跟节点入队,把队列中的队首出队,将这个出队相关的节点入队,这样循环,一直到队列为空。
1 /* 2 * @Description: 3 * @Version: 1.0 4 * @Autor: longbs 5 * 层次构建 6 */ 7 class Node { 8 constructor (data = '#') { 9 this.data = data 10 this.lNode = null 11 this.rNode = null 12 } 13 } 14 15 class BiTreeByLevel { 16 root = null 17 constructor () { 18 this.root = null 19 } 20 createNode (nodeList) { 21 let queue = [] 22 if (!this.root) { 23 let nodeValue = nodeList.shift() 24 this.root = new Node(nodeValue) 25 queue.push(this.root) 26 } 27 while (queue.length) { 28 // 将队列队首出队,这个是树的跟节点或者子树的跟节点 29 let head= queue.shift() 30 // 找到相关的在入队 31 let nodeValue = nodeList.shift() 32 // 构建左节点 33 if (nodeValue !== '#') { 34 head.lNode = new Node(nodeValue) 35 queue.push(head.lNode) 36 } 37 // 右节点 38 nodeValue = nodeList.shift() 39 if (nodeValue !== '#') { 40 head.rNode = new Node(nodeValue) 41 queue.push(head.rNode) 42 } 43 } 44 } 45 } 46 47 let arr = ['A','B','C','D','E','F','G','#','#','#','#','#','#','#','#'] 48 let bi = new BiTreeByLevel(arr) 49 bi.createNode(arr) 50 console.log(bi.root)
今天先到这里吧,后面把二叉树先序、中序、后序、层次遍历,查找二叉树、红黑树补上。