leet-code/symmetric-tree/sol.go

39 lines
712 B
Go

package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
/**
* 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
}
queue := []*TreeNode{root}
for len(queue) != 0 {
l := len(queue)
current := queue
queue = queue[l:]
for idx, node := range current {
if (node == nil && current[l-idx-1] != nil) ||
(node != nil && current[l-idx-1] == nil) ||
(node != nil && node.Val != current[l-idx-1].Val) {
return false
}
if node != nil {
queue = append(queue, node.Left, node.Right)
}
}
}
return true
}