七叶笔记 » golang编程 » Golang 刷题Leetcode 101. Symmetric Tree

Golang 刷题Leetcode 101. Symmetric Tree

题目:Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

判断一颗 二叉树 是否左右对称

思路

把一棵树当成两颗来处理,递归判断AB两棵树的左右子树是否对称相等

code

type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func isSymmetric(root *TreeNode) bool {
return isMirror(root, root)
}
func isMirror(t1 *TreeNode, t2 *TreeNode) bool {
if t1 ==  nil  && t2 == nil {
return true
}
if t1 == nil || t2 == nil {
return false
}
return t1.Val == t2.Val && isMirror(t1.Right, t2.Left) && isMirror(t2.Left, t1.Right)
}
 

更多内容请移步我的repo:

相关文章