1. 1. 生成二叉树
  2. 2. 遍历二叉树

生成二叉树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class TreeNode {
constructor(val) {
this.value = val;
this.left = this.right = null;
}
}
let root = new TreeNode('root');
const createTree = (node,index = 0) => {
if (index > 5) {
return
}
node.left = new TreeNode(`left${index}`);
node.right = new TreeNode(`right${index}`);
createTree(node.left, index + 1);
createTree(node.right, index + 1);
}
createTree(root);

遍历二叉树

1
2
3
4
5
6
7
8
9
const preorder = node => {
if (!node) {
return
}
console.log(node.value);
preorder(node.left);
preorder(node.right);
}
preorder(root);