Skip to content

Latest commit

 

History

History
75 lines (55 loc) · 1.21 KB

100.md

File metadata and controls

75 lines (55 loc) · 1.21 KB

Same Tree

题目

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

思路

key: 先序遍历,中序遍历,后续遍历
注意:针对nil情况的处理。

代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSameTree(p *TreeNode, q *TreeNode) bool {
    if (p == nil && q==nil) {
        return true
    }
    if (p == nil && q != nil) || (p != nil && q == nil) || (p.Val != q.Val) {
        return false
    }
    if !isSameTree(p.Left, q.Left) {
        return false
    }
    if !isSameTree(p.Right, q.Right) {
        return false
    }
    return true
}