LeetCode 94. Binary Tree Inorder Traversal
2022.07.18

問題

typescript

typescript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function help(root: TreeNode | null, res: Array<number>) {
  if (!root) return
  if (root.left) help(root.left, res)
  res.push(root.val)
  if (root.right) help(root.right, res)
}

function inorderTraversal(root: TreeNode | null): number[] {
  let res = []
  help(root, res)
  return res
}