树简介
- 分层数据的抽象模型 - DOM树,级联选择组件,树形控件
- js没有树但是可以用Array和Object构建树
树的常用操作
- 深度/广度优先遍历
- 先中后序遍历
树的深度优先遍历(尽可能深的搜索树的分支—递归)
const tree ={val:'a',children:[{val:'b',children:[{val:'c',children:[]},{val:'d',children:[]}]},{val:'e',children:[{val:'f',children:[]},{val:'g',children:[]}]}]}let arr = [1,56,333];console.log(arr.pop())const dfs = function(root){console.log(root.val);root.children.forEach((item)=>{dfs(item)})}dfs(tree)
树的广度优先遍历(优先遍历离根节点最近的节点)
1.新建一个队列,把根节点入队
2.对头出队并访问
3.把队头的children挨个入队
4.重复2,3直到队列为空
const tree ={val:'a',children:[{val:'b',children:[{val:'c',children:[]},{val:'d',children:[]}]},{val:'e',children:[{val:'f',children:[]},{val:'g',children:[]}]}]}
二叉树
1.树的每个节点最多只能有两个子节点
2.js中通常用Object来模拟二叉树
const binaryTree = {val:'123',left:{val:55,left:null,right:null},right:{val:66,left:null,right:null}}
二叉树先序遍历(算法口诀)
1.访问根节点
2.对根节点的左子树进行先序遍历
3.对根节点的右子树进行先序遍历
const bt = {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}}}const preorder = (root)=>{if(!root){ return }console.log(root.val);preorder(root.left);preorder(root.right);}preorder(bt)
二叉树中序遍历(算法口诀)
1.对根节点左子树进行中序遍历
2.访问根节点
3.对根节点的右子树进行中序遍历
const bt = {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}}}const inorder = (root)=>{if(!root){ return }inorder(root.left);console.log(root.val);inorder(root.right);}inorder(bt)
二叉树中序遍历(算法口诀)
1.对根节点左子树进行中序遍历
2.访问根节点
3.对根节点的右子树进行中序遍历
const bt = {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}}}const postorder = (root)=>{if(!root){ return }postorder(root.left);postorder(root.right);console.log(root.val);}postorder(bt)
二叉树最大深度-104.
(深度优先遍历)
1.求最大深度,考虑使用深度优先遍历
2.深度优先遍历过程中,记录每个节点所在的层级,找出最大的层级即可。
const maxDepth = function(root){let res = 0;const defs = (n,l)=>{if(!n){ return; };if(!n.left && !n.right){res = Math.max(res,l)}defs(n.left,l+1);defs(n.right,l+1);}defs(root,1);return res}
二叉树最小深度-111.
(广度优先遍历)
1.广度优先遍历整个树,并且记录每个节点的层级
2.遇到叶子节点,返回层级节点,停止遍历
const minDepth = function(root){if(!root){return 0;}const q = [[root,l]];while(q.length){const [n,l] = q.shift();if(!n.left && !n.right){return l}if(n.left){ q.push([n.left,l+1]) };if(n.right){ q.push([n.right,l+1]) };}}
二叉树层序遍历-102.
(广度优先遍历)
const minDepth = function(root){if(!root){return 0;}const q = [[root,l]];while(q.length){const [n,l] = q.shift();if(!n.left && !n.right){return l}if(n.left){ q.push([n.left,l+1]) };if(n.right){ q.push([n.right,l+1]) };}}
路径总和-112.
(深度优先遍历)
const hasPathSum = ()=>{if(!root){return false}let res = false}
