特点
- 一种分层数据的抽象模型
- 前端中常见的树:DOM、树、级联选择、树形控件
- JS中没有树,但可用object、array构建树
-
深度优先遍历(DFS) & 广度优先遍历(BFS)
深度优先遍历定义
遍历方法
访问根节点
- 对根节点的children挨个进行深度优先遍历
- 就是递归
```javascript
const tree = {
val: ‘a’,
children: [
{
], }, {val: 'b',children: [{val: 'd',children: [],},{val: 'e',children: [],},
], }, ], }val: 'c',children: [{val: 'f',children: [],},{val: 'g',children: [],},
const dfs = (root) => { console.log(root.val) root.children.forEach(dfs) }
dfs(tree);
<a name="W0wLQ"></a>## 广度优先遍历定义先访问离根节点最近的节点<br /><a name="YY36z"></a>### 遍历方法1. 新建一个队列,把根节点入队1. 把队头(根节点a)出队并访问1. 把队头(根节点a)的children(b,c)挨个入队1. 重复第二、三步,直到队列为空```javascriptconst tree = {val: 'a',children: [{val: 'b',children: [{val: 'd',children: [],},{val: 'e',children: [],},],},{val: 'c',children: [{val: 'f',children: [],},{val: 'g',children: [],},],},],}const bfs = (root) => {const q = [root]while(q.length > 0){const n = q.shift()console.log(n.val)n.children.forEach(child => {q.push(child)})}}
<递归版>二叉树的先中后序遍历
二叉树
- 树中每个节点最只能有两个子节点
- JS中通常用object模拟二叉树
<递归>先序遍历(preorder)
- 访问根节点
- 对跟几点的左子树进行先序遍历
- 对根节点的右子树进行先序遍历

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,rught: null,}}}const preorder = (root) => {if(!root) returnconsole.log(root.val)preorder(root.left)preorder(root.right)}
<递归>中序遍历(inorder)
- 对根节点的左子树进行中序遍历
- 访问根节点
- 对根节点的右子树进行中序遍历

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,rught: null,}}}const inorder = (root) => {if(!root) returninorder(root.left)console.log(root.val)inorder(root.right)}
<递归>后序遍历(postorder)
- 对根节点的左子树进行后序遍历
- 对根节点的右子树进行后序遍历
- 访问根节点

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,rught: null,}}}const postorder = (root) => {if(!root) returnpostorder(root.left)postorder(root.right)console.log(root.val)}
<非递归版>二叉树的先中后序遍历
先序遍历
const preorder = (root) => {if(!root) returnconst stack = [root]while (stack.length){const n = stack.pop()console.log(n.val)if(n.right) stack.push(n.right)if(n.left) stack.push(n.left)}}
中序遍历
const inorder = (root) => {if(!root) returnconst stack = []let p = rootwhile (stack.length || p){while(p){stack.push(p)p = p.left}const n = stack.pop()console.log(n.val)p = n.right}}
后序遍历
const postorder = (root) => {if(!root) returnconst outputStack = []const stack = [root]while (stack.length){const n = stack.pop()outputStack.push(n)if(n.left) stack.push(n.left)if(n.right) stack.push(n.right)}while(outputStack.length){const n = outputStack.pop()console.log(n.val)}}
应用场景
1. leetcode104:二叉树的最大深度
给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。
示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回它的最大深度 3 。
思路:
- 深度优先遍历
- 记录深度并对比,返回最大值
/*** 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 maxDepth = function(root) {let res = 0const dfs = (root, l) => {if(!root) returnif(!root.left && !root.right) res = Math.max(res,l)dfs(root.left,l+1)dfs(root.right,l+1)}dfs(root,1)return res};
2. leetcode111:二叉树的最小深度
给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明:叶子节点是指没有子节点的节点。
输入: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) => {
} dfs(root,1) return res };if(!root) returnif(!root.left && !root.right) res = res ? Math.min(res,l) : ldfs(root.left,l+1)dfs(root.right,l+1)
// 广度优先遍历
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]) } };
<a name="N3UIT"></a>## 3. leetcode102:二叉树的层序遍历> 给你二叉树的根节点 root ,返回其节点值的 **层序遍历** 。 (即逐层地,从左到右访问所有节点)。> **示例 1:**> > **输入:**root = [3,9,20,null,null,15,7] **输出:**[[3],[9,20],[15,7]]> (是一层一层的保存,并不是一棵树的左右节点为一个数组)思路:<br />广度优先遍历- 方法一:遍历时统计层级,层级相同则push进同一个数组```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 levelOrder = function(root) {if(!root) return []const resArr = []const p = [[root,0]]while(p.length){let [n,l] = p.shift()!resArr[l] ? resArr.push([n.val]) : resArr[l].push(n.val)if(n.left) p.push([n.left,l+1])if(n.right) p.push([n.right,l+1])}return resArr};
方法二:广度优先遍历,每次循环只保存当前层级的节点
var levelOrder = function(root) {if(!root) return []const resArr = []const p = [root]while(p.length){let len = p.length //父节点的数量resArr.push([])while(len--){let n = p.shift()resArr[resArr.length - 1].push(n.val) //将上一层的所有节点放到res的最后一个数组if(n.left) p.push(n.left)if(n.right) p.push(n.right)}}return resArr};
4. leetcode94: 二叉树的中序遍历
给定一个二叉树的根节点 root ,返回它的 中序 遍历。 示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]方法一:非递归版
/*** 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 inorderTraversal = function(root) {if(!root) return []const stack = []const res = []let n = rootwhile(stack.length || n){while(n){stack.push(n)n = n.left}let p = stack.pop()res.push(p.val)n = p.right}return res};
方法二:递归版
var inorderTraversal = function(root) {const res = []const rec = (n) => {if(!n) returnrec(n.left)res.push(n.val)rec(n.right)}rec(root)return res};
5. leetcode112:路径总和
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true
解释:等于目标和的根节点到叶节点路径如上图所示。
思路:
- 深度优先遍历
- 每次遍历计算路径总和
- 通过flag变量返回是否存在
var hasPathSum = function(root, targetSum) {if(!root) return falselet res = falseconst dfs = (root,l) => {if(!root.left && !root.right && l === targetSum) res = trueif(root.left) dfs(root.left, l + root.left.val)if(root.right) dfs(root.right, l + root.right.val)}dfs(root,root.val)return res};
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, []) ```
