题目:Same Tree
Given two binary trees, write a function to check if they are the same or not.
判断两个 二叉树 是否完全相同
思路
二叉树的题目,最常见的解法就是递归
code
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) {
return false
}
if p.Val != q.Val {
return false
}
return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
}
更多内容请移步我的repo: