[Leetcode]6.镜像二叉树判断
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
思想:递归判断,判断传入的两个结点是否为双空或值相等,否则判false,如果为true,则传入左结点的左孩子和右节点的右孩子,左节点的右孩子和右节点的左孩子继续判断.
主函数判断根节点是否为空,并传入根节点的左右孩子即可.
/** * 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 test(root.Left,root.Right) } func test(l *TreeNode,r *TreeNode) bool{ if l==nil&&r==nil{ return true }else if l==nil||r==nil{ return false }else if l.Val!=r.Val{ return false } return test(l.Left,r.Right)&&test(l.Right,r.Left) }
题目来源:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof