特点

  1. 一种分层数据的抽象模型
  2. 前端中常见的树:DOM、树、级联选择、树形控件
  3. JS中没有树,但可用object、array构建树
  4. 树的常用操作:深度/广度优先遍历、先中后序遍历

    深度优先遍历(DFS) & 广度优先遍历(BFS)

    深度优先遍历定义

    尽可能深的搜索树的分支
    image.png

    遍历方法

  5. 访问根节点

  6. 对根节点的children挨个进行深度优先遍历
  7. 就是递归 ```javascript const tree = { val: ‘a’, children: [ {
    1. val: 'b',
    2. children: [
    3. {
    4. val: 'd',
    5. children: [],
    6. },
    7. {
    8. val: 'e',
    9. children: [],
    10. },
    ], }, {
    1. val: 'c',
    2. children: [
    3. {
    4. val: 'f',
    5. children: [],
    6. },
    7. {
    8. val: 'g',
    9. children: [],
    10. },
    ], }, ], }

const dfs = (root) => { console.log(root.val) root.children.forEach(dfs) }

dfs(tree);

  1. <a name="W0wLQ"></a>
  2. ## 广度优先遍历定义
  3. 先访问离根节点最近的节点<br />![image.png](https://cdn.nlark.com/yuque/0/2022/png/25618940/1643341524107-7c7451e1-9090-4ada-9255-d80c3f9206e1.png#clientId=u8f9b9bce-ca1c-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=285&id=u6725478b&margin=%5Bobject%20Object%5D&name=image.png&originHeight=570&originWidth=304&originalType=binary&ratio=1&rotation=0&showTitle=false&size=57150&status=done&style=none&taskId=u2185f892-d940-46dd-aa54-59281efdbf8&title=&width=152)
  4. <a name="YY36z"></a>
  5. ### 遍历方法
  6. 1. 新建一个队列,把根节点入队
  7. 1. 把队头(根节点a)出队并访问
  8. 1. 把队头(根节点a)的children(b,c)挨个入队
  9. 1. 重复第二、三步,直到队列为空
  10. ```javascript
  11. const tree = {
  12. val: 'a',
  13. children: [
  14. {
  15. val: 'b',
  16. children: [
  17. {
  18. val: 'd',
  19. children: [],
  20. },
  21. {
  22. val: 'e',
  23. children: [],
  24. },
  25. ],
  26. },
  27. {
  28. val: 'c',
  29. children: [
  30. {
  31. val: 'f',
  32. children: [],
  33. },
  34. {
  35. val: 'g',
  36. children: [],
  37. },
  38. ],
  39. },
  40. ],
  41. }
  42. const bfs = (root) => {
  43. const q = [root]
  44. while(q.length > 0){
  45. const n = q.shift()
  46. console.log(n.val)
  47. n.children.forEach(child => {
  48. q.push(child)
  49. })
  50. }
  51. }

<递归版>二叉树的先中后序遍历

二叉树

  • 树中每个节点最只能有两个子节点
  • JS中通常用object模拟二叉树

image.png

<递归>先序遍历(preorder)

  1. 访问根节点
  2. 对跟几点的左子树进行先序遍历
  3. 对根节点的右子树进行先序遍历

image.png

  1. const bt = {
  2. val: 1,
  3. left: {
  4. val: 2,
  5. left: {
  6. val: 4,
  7. left: null,
  8. right: null,
  9. },
  10. right: {
  11. val: 5,
  12. left: null,
  13. right: null,
  14. }
  15. },
  16. right: {
  17. val: 3,
  18. left:{
  19. val: 6,
  20. left: null,
  21. right: null,
  22. },
  23. right: {
  24. val: 7,
  25. left: null,
  26. rught: null,
  27. }
  28. }
  29. }
  30. const preorder = (root) => {
  31. if(!root) return
  32. console.log(root.val)
  33. preorder(root.left)
  34. preorder(root.right)
  35. }

<递归>中序遍历(inorder)

  1. 对根节点的左子树进行中序遍历
  2. 访问根节点
  3. 对根节点的右子树进行中序遍历

image.png

  1. const bt = {
  2. val: 1,
  3. left: {
  4. val: 2,
  5. left: {
  6. val: 4,
  7. left: null,
  8. right: null,
  9. },
  10. right: {
  11. val: 5,
  12. left: null,
  13. right: null,
  14. }
  15. },
  16. right: {
  17. val: 3,
  18. left:{
  19. val: 6,
  20. left: null,
  21. right: null,
  22. },
  23. right: {
  24. val: 7,
  25. left: null,
  26. rught: null,
  27. }
  28. }
  29. }
  30. const inorder = (root) => {
  31. if(!root) return
  32. inorder(root.left)
  33. console.log(root.val)
  34. inorder(root.right)
  35. }

<递归>后序遍历(postorder)

  1. 对根节点的左子树进行后序遍历
  2. 对根节点的右子树进行后序遍历
  3. 访问根节点

image.png

  1. const bt = {
  2. val: 1,
  3. left: {
  4. val: 2,
  5. left: {
  6. val: 4,
  7. left: null,
  8. right: null,
  9. },
  10. right: {
  11. val: 5,
  12. left: null,
  13. right: null,
  14. }
  15. },
  16. right: {
  17. val: 3,
  18. left:{
  19. val: 6,
  20. left: null,
  21. right: null,
  22. },
  23. right: {
  24. val: 7,
  25. left: null,
  26. rught: null,
  27. }
  28. }
  29. }
  30. const postorder = (root) => {
  31. if(!root) return
  32. postorder(root.left)
  33. postorder(root.right)
  34. console.log(root.val)
  35. }

<非递归版>二叉树的先中后序遍历

先序遍历

  1. const preorder = (root) => {
  2. if(!root) return
  3. const stack = [root]
  4. while (stack.length){
  5. const n = stack.pop()
  6. console.log(n.val)
  7. if(n.right) stack.push(n.right)
  8. if(n.left) stack.push(n.left)
  9. }
  10. }

中序遍历

  1. const inorder = (root) => {
  2. if(!root) return
  3. const stack = []
  4. let p = root
  5. while (stack.length || p){
  6. while(p){
  7. stack.push(p)
  8. p = p.left
  9. }
  10. const n = stack.pop()
  11. console.log(n.val)
  12. p = n.right
  13. }
  14. }

后序遍历

  1. const postorder = (root) => {
  2. if(!root) return
  3. const outputStack = []
  4. const stack = [root]
  5. while (stack.length){
  6. const n = stack.pop()
  7. outputStack.push(n)
  8. if(n.left) stack.push(n.left)
  9. if(n.right) stack.push(n.right)
  10. }
  11. while(outputStack.length){
  12. const n = outputStack.pop()
  13. console.log(n.val)
  14. }
  15. }

应用场景

1. leetcode104:二叉树的最大深度

给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。

示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回它的最大深度 3 。

思路:

  • 深度优先遍历
  • 记录深度并对比,返回最大值
    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @return {number}
    12. */
    13. var maxDepth = function(root) {
    14. let res = 0
    15. const dfs = (root, l) => {
    16. if(!root) return
    17. if(!root.left && !root.right) res = Math.max(res,l)
    18. dfs(root.left,l+1)
    19. dfs(root.right,l+1)
    20. }
    21. dfs(root,1)
    22. return res
    23. };

    2. leetcode111:二叉树的最小深度

    给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明:叶子节点是指没有子节点的节点。 树 - 图6 输入:root = [3,9,20,null,null,15,7] 输出:2

思路:

  • 深度优先遍历同104,只不过是判断最小值
  • 广度优先遍历:计算层级,遇到第一个叶子节点直接返回层级结果 ```javascript /**
    • Definition for a binary tree node.
    • function TreeNode(val, left, right) {
    • this.val = (val===undefined ? 0 : val)
    • this.left = (left===undefined ? null : left)
    • this.right = (right===undefined ? null : right)
    • } / /*
    • @param {TreeNode} root
    • @return {number} */ // 深度优先遍历 var minDepth = function(root) { let res = 0 const dfs = (root, l) => {
      1. if(!root) return
      2. if(!root.left && !root.right) res = res ? Math.min(res,l) : l
      3. dfs(root.left,l+1)
      4. dfs(root.right,l+1)
      } dfs(root,1) return res };

// 广度优先遍历

var minDepth = function(root) { if(!root) return 0 const p = [[root,1]] while(p.length){ const [n,l] = p.shift() if(!n.left && !n.right) return l if(n.left) p.push([n.left,l+1]) if(n.right) p.push([n.right,l+1]) } };

  1. <a name="N3UIT"></a>
  2. ## 3. leetcode102:二叉树的层序遍历
  3. > 给你二叉树的根节点 root ,返回其节点值的 **层序遍历** 。 (即逐层地,从左到右访问所有节点)。
  4. > **示例 1:**
  5. > ![](https://cdn.nlark.com/yuque/0/2022/jpeg/25618940/1644316468997-e86209fc-010f-48c5-9dcd-4343098c8f2c.jpeg#clientId=u7be1eeee-195c-4&crop=0&crop=0&crop=1&crop=1&from=paste&id=u882badbb&margin=%5Bobject%20Object%5D&originHeight=302&originWidth=277&originalType=url&ratio=1&rotation=0&showTitle=false&status=done&style=none&taskId=u0c967af6-a179-4766-b7e0-d141b428f66&title=)
  6. > **输入:**root = [3,9,20,null,null,15,7] **输出:**[[3],[9,20],[15,7]]
  7. > (是一层一层的保存,并不是一棵树的左右节点为一个数组)
  8. 思路:<br />广度优先遍历
  9. - 方法一:遍历时统计层级,层级相同则push进同一个数组
  10. ```javascript
  11. /**
  12. * Definition for a binary tree node.
  13. * function TreeNode(val, left, right) {
  14. * this.val = (val===undefined ? 0 : val)
  15. * this.left = (left===undefined ? null : left)
  16. * this.right = (right===undefined ? null : right)
  17. * }
  18. */
  19. /**
  20. * @param {TreeNode} root
  21. * @return {number[][]}
  22. */
  23. var levelOrder = function(root) {
  24. if(!root) return []
  25. const resArr = []
  26. const p = [[root,0]]
  27. while(p.length){
  28. let [n,l] = p.shift()
  29. !resArr[l] ? resArr.push([n.val]) : resArr[l].push(n.val)
  30. if(n.left) p.push([n.left,l+1])
  31. if(n.right) p.push([n.right,l+1])
  32. }
  33. return resArr
  34. };
  • 方法二:广度优先遍历,每次循环只保存当前层级的节点

    1. var levelOrder = function(root) {
    2. if(!root) return []
    3. const resArr = []
    4. const p = [root]
    5. while(p.length){
    6. let len = p.length //父节点的数量
    7. resArr.push([])
    8. while(len--){
    9. let n = p.shift()
    10. resArr[resArr.length - 1].push(n.val) //将上一层的所有节点放到res的最后一个数组
    11. if(n.left) p.push(n.left)
    12. if(n.right) p.push(n.right)
    13. }
    14. }
    15. return resArr
    16. };

    4. leetcode94: 二叉树的中序遍历

    给定一个二叉树的根节点 root ,返回它的 中序 遍历。 示例 1: 树 - 图7 输入:root = [1,null,2,3] 输出:[1,3,2]

  • 方法一:非递归版

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @return {number[]}
    12. */
    13. var inorderTraversal = function(root) {
    14. if(!root) return []
    15. const stack = []
    16. const res = []
    17. let n = root
    18. while(stack.length || n){
    19. while(n){
    20. stack.push(n)
    21. n = n.left
    22. }
    23. let p = stack.pop()
    24. res.push(p.val)
    25. n = p.right
    26. }
    27. return res
    28. };
  • 方法二:递归版

    1. var inorderTraversal = function(root) {
    2. const res = []
    3. const rec = (n) => {
    4. if(!n) return
    5. rec(n.left)
    6. res.push(n.val)
    7. rec(n.right)
    8. }
    9. rec(root)
    10. return res
    11. };

    5. leetcode112:路径总和

    给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。

    叶子节点 是指没有子节点的节点。

    示例 1: image.png 输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 输出:true 解释:等于目标和的根节点到叶节点路径如上图所示。

思路:

  • 深度优先遍历
  • 每次遍历计算路径总和
  • 通过flag变量返回是否存在
    1. var hasPathSum = function(root, targetSum) {
    2. if(!root) return false
    3. let res = false
    4. const dfs = (root,l) => {
    5. if(!root.left && !root.right && l === targetSum) res = true
    6. if(root.left) dfs(root.left, l + root.left.val)
    7. if(root.right) dfs(root.right, l + root.right.val)
    8. }
    9. dfs(root,root.val)
    10. return res
    11. };

    6. 遍历JSON的所有节点值

    思路:深度优先遍历 ```javascript const json = { a: { b: { c:1 } }, d: [1, 2], }

const dfs = (n, path) => { console.log(n,path) Object.keys(n).forEach( k => { dfs(n[k],path.concat(k)) }) }

dfs(json, []) ```