Skip to content

617. 合并二叉树 #87

@Geekhyt

Description

@Geekhyt

原题链接

dfs 递归

在 root1 上直接修改,将两个树对应的节点相加后,赋值给 root1,然后递归执行两个左右子树。

const mergeTrees = function(root1, root2) {
    const preOrder = function(root1, root2) {
        if (!root1) return root2
        if (!root2) return root1
        root1.val += root2.val
        root1.left = preOrder(root1.left, root2.left)
        root1.right = preOrder(root1.right, root2.right)
        return root1
    }
    return preOrder(root1, root2)
}
  • 时间复杂度: O(min(m,n))
  • 空间复杂度: O(min(m,n))

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy