Skip to main content

二叉树的中序遍历

Tips

题目类型: Tree

题目

手写二叉树的中序遍历.

示例

输入: TreeNode 实例

输出: 每个 TreeNode 节点的 val 组成的数组

题解

这没啥可说的了, 基本功. 💔

/**
* 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) {
const stack = []
const res = []

while (stack.length !== 0 || root !== null) {
if (root !== null) {
stack.push(root)
root = root.left
} else {
root = stack.pop()
res.push(root.val)
root = root.right
}
}

return res
}