LC-二叉树的中序遍历

题目描述

二叉树的中序遍历

给定一个二叉树,返回它的中序遍历。

1
2
3
4
5
6
7
8
输入: [1,null,2,3]
1
\
2
/
3

输出: [1,3,2]

代码实现

递归

对于中序遍历,就是 左根右,递归还是很简单的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 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 result = [];
function recursive(root) {
if (root) {
recursive(root.left);
result.push(root.val);
recursive(root.right);
}
}
recursive(root);
return result;
};

栈 + 迭代

如果 root 存在,那么将它放入 stack 中,并且继续指向左子树。

如果 root 不存在,那么取出栈顶元素,将其值放入 res,并将 root 指向右子树。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 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 result = [];
let stack = [];

while (stack.length || root) {
if (root) {
stack.push(root);
root = root.left;
} else {
let node = stack.pop();
res.push(node.val);
root = node.right;
}
}
return result;
};