Skip to content

100. 相同的树 #16

Description

@Geekhyt

原题链接

深度优先搜索 DFS

1.如果两个二叉树都为空,则它们相同返回 true。
2.如果两个二叉树中有一个为空,则它们不同返回 false。
3.如果两个二叉树都不为空,首先判断根节点是否相同,不同则返回 false。
4.如果两个二叉树的根节点相同,则分别递归判断其左右子树是否相同。

const isSameTree = function(p, q) {
    if (p === null && q === null) return true;
    if (p === null || q === null) return false;
    if (p.val !== q.val) return false;
    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};
  • 时间复杂度: O(min(m, n))
  • 空间复杂度: O(min(m, n))

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions