# JS实现二叉树的前序、中序、后续、层序遍历

## 前序遍历

LeetCode题目

### 递归

``````var preorderTraversal = function(root) {
const res = [];
// 递归函数
function _preorder(node) {
if (!node) return;
res.push(node.val);
_preorder(node.left);
_preorder(node.right);
}
_preorder(root);
return res;
};

### 迭代

``````var preorderTraversal = function(root) {
if (!root) return [];
const stack = [root];
const res = [];
while(stack.length) {
// 出栈
const cur = stack.pop();
res.push(cur.val);
// 子节点存在压入栈中，先右再左
cur.right && stack.push(cur.right);
cur.left && stack.push(cur.left);
}
return res;
};

## 中序遍历

LeetCode题目

### 递归

``````var inorderTraversal = function(root) {
const res = [];
// 递归函数
function _inorder(node) {
if (!node) return;
_inorder(node.left);
res.push(node.val);
_inorder(node.right);
}
_inorder(root);
return res;
};

### 迭代

``````var inorderTraversal = function(root) {
if (!root) return [];
const stack = [];
let cur = root;
const res = [];
while (stack.length || cur) {
// 左节点都先压入栈
while (cur) {
stack.push(cur);
cur = cur.left;
}
const node = stack.pop();
res.push(node.val);
if (node.right != null) {
cur = node.right;
}
}
return res;
};

## 后序遍历

LeetCode题目

### 递归

``````var postorderTraversal = function(root) {
const res = [];
// 递归函数
function _postorder(node) {
if (!node) return;
_postorder(node.left);
_postorder(node.right);
res.push(node.val);
}
_postorder(root);
return res;
};

### 迭代

``````var postorderTraversal = function(root) {
if (!root) return null;
const res = [];
const stack = [root];
while (stack.length) {
const cur = stack.pop();
// 总是头部插入，先被插入的在后面。
res.unshift(cur.val);
cur.left && stack.push(cur.left);
cur.right && stack.push(cur.right);
}

return res;
};

## 层序遍历

LeetCode题目

### 递归

``````var levelOrder = function(root) {
const res = [];
function _levelOrder(node, level) {
if (!node) return null;
// 当前层数组初始化
res[level] =  res[level] || [];
res[level].push(node.val);
// 下一层 +1
_levelOrder(node.left, level + 1);
_levelOrder(node.right, level + 1);
}
_levelOrder(root, 0);

return res;
};

### 迭代

``````var levelOrder = function(root) {
if (root == null) return [];
const ans = [];
let level = 0;
const queue = [root];
while(queue.length) {
ans.push([]);
const len = queue.length;
// 通过遍历，提前执行完一层的所有元素，层级level就可以+1
for (let i = 0; i < len; i++) {
const node = queue.shift();
ans[level].push(node.val);
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
level++;
}
return ans;
};