Skip to content

Latest commit

 

History

History
85 lines (54 loc) · 1.34 KB

0100.same-tree.md

File metadata and controls

85 lines (54 loc) · 1.34 KB

0100.Same-Tree

Description

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

Tags: Tree, Depth-first Search

题意

比较两棵二叉树是否相同

题解

思路1

任意搜索比较二叉树及诶单即可

func isSameTree(p *TreeNode, q *TreeNode) bool {
    if p == nil && q == nil {
        return true
    }

    if p == nil || q == nil {
        return false
    }

    if p.Val == q.Val {
        return isSameTree(p.Left, q.Left) &&
            isSameTree(p.Right, q.Right)
    }

    return false
}

思路2

思路2 ```go

```

结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:awesome-golang-algorithm