题目
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
解题思路
如果树不是空树,则问题变为判断根树的两个子树t1,t2是否是镜像
将t2左右翻转后和t1比较,如果t1,t2相等,则原数是镜像树
代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func ReverseTree(t *TreeNode) {
if nil == t {
return
}
t.Left, t.Right = t.Right, t.Left
ReverseTree(t.Left)
ReverseTree(t.Right)
}
func EqualTree(t1, t2 *TreeNode) bool {
if nil == t1 && nil == t2 {
return true
} else if nil != t1 && nil == t2 {
return false
} else if nil == t1 && nil != t2 {
return false
}
if t1.Val != t2.Val {
return false
}
ok1 := EqualTree(t1.Left, t2.Left)
if !ok1 {
return false
}
ok2 := EqualTree(t1.Right, t2.Right)
if !ok2 {
return false
}
return true
}
func isSymmetric(root *TreeNode) bool {
if nil == root {
return true
}
left := root.Left
ReverseTree(root.Right)
equal := EqualTree(left, root.Right)
if equal {
return true
} else {
return false
}
}