/** * 深度优先搜索: DFS(Depth First Search) * 深度优先搜索:也就是一条路走到黑,然后再往回走,看看是否还有其他路径 * 分类:二叉树的前、中、后序遍历 * 前序遍历:根节点 -> 左子树 -> 右子树 * 中序遍历:左子树 -> 根节点 -> 右子树 * 后序遍历:左子树 -> 右子树 -> 根节点 */class Node { constructor(val) { this.key = val; this.left = null; this.right = null; }}let root = null;let arr = [];
// 前序遍历:根节点 -> 左节点 -> 右节点const preOrder = node => { if (node === null) return; arr.push(node.key); preOrder(node.left); preOrder(node.right); return arr;};
// 中序遍历:左节点 -> 根节点 -> 右节点const inOrder = node => { if (node === null) return; inOrder(node.left); arr.push(node.key); inOrder(node.right); return arr;};
// 后续遍历:左节点 -> 右节点 -> 根节点const postOrder = node => { if (node === null) return; postOrder(node.left); postOrder(node.right); arr.push(node.key); return arr;};
// test:root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.right.right = new Node(6);root.left.left = new Node(4);root.left.right = new Node(5);/** * Binary Tree: 1 2 3 4 5 6 */
// console.log(preOrder(root)); // [ 1, 2, 4, 5, 3, 6 ]// console.log(inOrder(root)); // [ 4, 2, 5, 1, 3, 6 ]// console.log(postOrder(root)); // [ 4, 5, 2, 6, 3, 1 ]
评论