操操操

对称二叉树golang版本

2023-08-20
1分钟阅读时长

对称二叉树golang版本

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func isSymmetric(root *TreeNode) bool {
	if root == nil {
		return true
	}
	// 如不为空,同时遍历左右两棵树
	return isSymmetrical(root.Left, root.Right)
}

func isSymmetrical(life, right *TreeNode) bool {
	if life == nil && right == nil {
		return true
	}
	if life == nil || right == nil {
		return false
	}
	if life.Val != right.Val {
		return false
	}
	return isSymmetrical(life.Left, right.Right) && isSymmetrical(life.Right, right.Left)
}
Avatar

Aisen

Be water,my friend.