二叉树的中序遍历,左——> 根——>右
递归实现
- Runtime: 68 ms, faster than 90.03%
- Memory Usage: 36.8 MB, less than 35.02%
1、递归过程会调用函数自身,导致函数调用栈的频繁进栈出栈,时间复杂度高,每次函数调用,需要在函数栈中分配内存空间以保存参数、返回地址以及临时变量,空间复杂度高,并且有可能存在重复计算。
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) {
var res = []
inorder(root, res)
return res
};
var inorder = function(root, res){
if (root !== null){
root.left && inorder(root.left, res)
res.push(root.val)
root.right && inorder(root.right, res)
}
else return
}
递归实现2
- Runtime: 72 ms, faster than 79.34%
- Memory Usage: 36.8 MB, less than 33.47%
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
if(!root) return []
let res = []
let recursive = function(node) {
if(node.left) recursive(node.left)
res.push(node.val)
if(node.right) recursive(node.right)
}
recursive(root)
return res
};
非递归实现
- Runtime: 76 ms, faster than 60.86%
- Memory Usage: 37.2 MB, less than 5.01%
当根节点非空时,将根节点入栈,左子节点入栈,直到为空时,该节点弹出,进入结果数组,然后根节点弹出,进入结果数组,对右子树进行遍历。
var inorderTraversal = function(root) {
var stack = []
var res = []
while(root !== null || stack.length !== 0){
if(root !== null){
stack.push(root)
root = root.left
} else{
root = stack.pop()
res.push(root.val)
root = root.right
}
}
return res
};
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
if(!root) return []
let stack = []
let res = []
let p = root
while(stack.length > 0 || p) {
if(p) {
stack.push(p)
p = p.left
} else {
let node = stack.pop()
res.push(node.val)
p = node.right
}
}
return res
};