1.以中序遍历为例
var inorderTraversal = function(root) {
if (!root) {
return []
}
const res = [];
const stack = [{mark: false,node: root}];
while(stack.length > 0) {
const {mark, node} = stack.pop();
if (node === null) {
continue;
}
if (!mark) {
// stack的顺序和遍历顺序相反 中序遍历 左、根、右 =====》 右、根、左
stack.push({mark: false, node: node.right});
stack.push({mark: true, node: node});
stack.push({mark: false, node: node.left});
} else {
res.push(node.val);
}
}
return res;
};