1. 总览
2. 题目
2.1 二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
2.2 二叉树的中序遍历
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
2.3 二叉树的后序遍历
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解法
1. 最普通的递归
1. 前序遍历
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
let nums = [];
let func = (root) => {
nums.push(root.val);
root.left && func(root.left);
root.right && func(root.right);
}
root && func(root);
return nums;
};
2. 中序遍历
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
let nums = [];
let func = (root) => {
root.left && func(root.left);
nums.push(root.val);
root.right && func(root.right);
}
root && func(root);
return nums;
};
3. 后序遍历
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
let nums = [];
let func = (root) => {
root.left && func(root.left);
root.right && func(root.right);
nums.push(root.val);
}
root && func(root);
return nums;
};
2. 使用栈来模拟递归
使用栈来模拟前序遍历递归
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
const list = [];
const stack = [];
root && stack.push(root);
while(stack.length > 0) {
const curNode = stack.pop();
list.push(curNode.val);
curNode.right && stack.push(curNode.right);
curNode.left && stack.push(curNode.left);
}
return list;
};
使用栈来模拟中序遍历递归
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
let list = [];
let stack = [];
let node = root;
while(node || stack.length) {
// 遍历左子树
while(node) {
stack.push(node);
node = node.left;
}
node = stack.pop();
list.push(node.val);
node = node.right;
}
return list;
};
使用栈来模拟后序遍历递归
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
const list = [];
const stack = [];
root && stack.push(root);
// 当根节点不为空的时候,将根节点入栈
while(stack.length > 0) {
let node = stack.pop();
// [根]
list.unshift(node.val);
// [左,右]
// [根] => [左,右,根]
node.left && stack.push(node.left);
node.right && stack.push(node.right);
}
return list;
};