孙晓聪
  • 最新
  • 博客
  • 书评
  • Binary Tree Inorder Traversal

    Description

    doc

    Solutions

    First Idea

    /**
     * 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) {
      if (!root) {
        return []
      }
    
      if (!root.left && !root.right) {
        return [root.val]
      }
    
      return [
        ...inorderTraversal(root.left),
        root.val,
        ...inorderTraversal(root.right),
      ]
    }
    
    • Time Complexity: O(n)
    • Space Complexity: O(n)

    Refined one

    /**
     * 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) {
      if (!root) {
        return []
      }
    
      return [
        ...inorderTraversal(root.left),
        root.val,
        ...inorderTraversal(root.right),
      ]
    }
    
    • Time Complexity: O(n)
    • Space Complexity: O(n)