【题目】 94. 二叉树的中序遍历
【题目考察】:二叉树、栈
【目标复杂度】: O(n)
【解法】:
/**
* 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) {
const res = [];
const stack = []
let cur = root;
while(cur !== null || stack.length!== 0) {
if (cur !== null) {
stack.push(cur);
cur = cur.left;
} else {
const top = stack.pop();
res.push(top.val);
cur = top.right;
}
}
return res;
};