编程题-检查二叉树对称
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
//思路类似使用栈括号对
var a []int
var b *TreeNode
func isSymmetric(root *TreeNode) bool {
if b == nil{
b = root
}
if root!=nil{
isSymmetric(root.Left)
if len(a)==0{
a = append(a,root.Val)
}else{
if root.Val != a[len(a)-1] && root != b{
a = append(a,root.Val)
}
if root.Val == a[len(a)-1] && root != b{
a = a[:len(a)-1]
}
}
isSymmetric(root.Right)
}
if len(a) == 0 || root == nil{
return true
}else{
return false
}
}
正确的做法:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
//思路类似使用栈括号对
//递归左树的左孩子与右树的右孩子对称
func isSymmetric(root *TreeNode) bool {
if root == nil{
return true
}
return Minlist(root,root)
}
func Minlist(r1 *TreeNode,r2 *TreeNode) bool{
if r1 == nil && r2 == nil{
return true
}
if (r1 == nil && r2 != nil)||(r2 == nil && r1 != nil){
return false
}
if r1.Val == r2.Val && Minlist(r1.Left,r2.Right) && Minlist(r1.Right,r2.Left){
return true
}else{
return false
}
}
静,静,静