树的结构
每层都有val和children
let tree = {val: 1,children: [{val: 2,children: [{val: 4, children:[]},{val: 5, children: []}]},{val: 3,children: [{val: 6, children:[]},{val: 7, children:[]},]}]}
树的遍历
- 深度优先遍历(递归)
const fun = (root) => {console.log(root.val)root.forEach(fun)}
- 广度优先遍历(数组模拟队列的使用,右进左出)
1、新建队列,根节点入队
2、把对头出队
3、把对头的children挨个入队
4、重复2、3步,直到队列为空为止
const fun = (root) => {let arr = [root]while(arr.length){const o = arr.shift()o.children.forEach(item => {console.log(o.val)arr.push(item)})}}
将数组转化成树
前提:每项中有id和pId,且有对应关系,根节点项id为null
const bidsList = [{parent: null, id: 1, text: '111'},{parent: null, id: 2, text: '222'},{parent: 1, id: 3, text: '1-1'},{parent: 1, id: 4, text: '1-2'},{parent: 2, id: 4, text: '2-1'},
]
function getTreeList (rootList, id, list) {for (let item of rootList) {if (item.parent === id ) {list.push(item)}}for (let i of list) {const flagItem = bidsList.find(si => {return si.parentId === i.id})if(flagItem) {i.children = []getTreeList(rootList, i.id, i.children)}}return list
}const treeData = getTreeList(bidsList, null, [])
console.log('treeData', treeData)
二叉树的结构
let binaryTree = {val: 1,left: {val: 2,left: {val: 4, left: null, right: null},right: {val: 5, left: null, right: null}},right: {val: 3,left: {val: 6, left: null, right: null},right: {val: 7, left: null, right: null}}}
二叉树的遍历
- 前序遍历(根左右1、2、4、5、3、6、7)
// 递归方式实现
let arr = []const fun = (node) => {if(node){arr.push(node.val)fun(node.left)fun(node.right)}}fun(binaryTree) console.log(arr)
//栈加循环方式实现
if(!root){return []}let arr = []let stack = [root]while(stack.length){let o = stack.pop()arr.push(o.val)o.right && arr.push(o.right)o.left && arr.push(o.left)}console.log(arr)
- 中序遍历(左根右4、2、5、1、6、3、7)
// 递归实现
let arr = []
const fn = (tree) => {if(!tree){return}fn(tree.left)arr.push(tree.val)fn(tree.right)
}
fn(binaryTree)
console.log(arr)// 栈加循环实现
let arr = []
let stack = []
let o = binaryTree
while(stack.length || o){while(o){stack.push(o)o = o.left}const n = stack.pop()arr.push(n.val)o = n.right
}
console.log(arr)
- 后序遍历(左右根4、5、2、6、7、3、1)
// 递归实现
let arr = []const fn = (node) => {if(node) {fn(node.left)fn(node.right)arr.push(node.val)}}fn(binaryTree)console.log(arr)// 栈加循环实现
let arr = []let stack = []while(stack.length){const o = stack.pop()arr.unshift(o)o.left && stack.push(o.left)o.right && stack.push(o.right)}console.log(arr)