2021-10-05:对称二叉树。给定一个二叉树,检查它是否是镜像对称的。例如,二叉树 [1,2,2,3,4,4,3] 是对称的。力扣101。
福大大 答案2021-10-05:
递归。head1的左节点 ==head2的右节点。head1的右节点 ==head2的左节点。
代码用golang编写。代码如下:
package main
import "fmt"
func main() {
head := &TreeNode{}
head.val = 1
head.left = &TreeNode{}
head.left.val = 2
head.right = &TreeNode{}
head.right.val = 2
head.left.left = &TreeNode{}
head.left.left.val = 3
head.right.right = &TreeNode{}
head.right.right.val = 3
ret := isSymmetric(head)
fmt.Println(ret)
}
type TreeNode struct {
val int
left *TreeNode
right *TreeNode
}
func isSymmetric(root *TreeNode) bool {
return isMirror(root, root)
}
// 一棵树是原始树 head1
// 另一棵是翻面树 head2
func isMirror(head1 *TreeNode, head2 *TreeNode) bool {
if head1 == nil && head2 == nil {
return true
}
if head1 != nil && head2 != nil {
return head1.val == head2.val && isMirror(head1.left, head2.right) && isMirror(head1.right, head2.left)
}
// 一个为空,一个不为空 false
return false
}
执行结果如下:
***
[左神java代码](