Saturday, March 4, 2023
Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
n
is a height of a treen
is a number of recusrsive calls in the stack/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSymmetric(root *TreeNode) bool {
return isEqual(root, root)
}
func isEqual(left *TreeNode, right *TreeNode) bool {
if left == nil && right == nil {
return true
}
if left == nil || right == nil {
return false
}
isCurrentEqual := left.Val == right.Val
isSymmetricLeft := isEqual(left.Left, right.Right)
isAsymmetricRight := isEqual(left.Right, right.Left)
return isCurrentEqual && isSymmetricLeft && isAsymmetricRight
}