# day12-使用JavaScript实现树的深度优先遍历和广度优先遍历

class TreeNode {
  constructor(val,left=null,right=null){
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

const root= new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

深度优先遍历

function dfs(node){
  if(node === null) return;
  console.log(node.val);
  dfs(node.left);
  dfs(node.right);
}
1
2
3
4
5
6

广度优先遍历

function bfs(root){
  if(root === null) return;
  const arr = [root];
  while(arr.length > 0){
    const node = arr.shift();
    console.log(node.val);
    if(node.left) arr.push(node.left);
    if(node.right) arr.push(node.right);
  }
}
1
2
3
4
5
6
7
8
9
10