LeetCode热题100道-Day07
- 使用递归,如果左树的左子树与右树的右子树对称,左树的右子树与右树的左子树对称,那么这个左树和右树就对称。
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null){
return false;
}
return check(root.left,root.right);
}
public boolean check(TreeNode left, TreeNode right){
if(left == null || right == null){
return left == right;
}
if(left.val != right.val){
return false;
}
return check(left.left,right.right) && check(left.right,right.left);
}
}
func isSymmetric(root *TreeNode) bool {
if root == nil {
return false
}
return check(root.Left,root.Right)
}
func check(left *TreeNode, right *TreeNode) bool{
if left == nil || right == nil {
return left == right
}
if left.Val != right.Val {
return false
}
return check(left.Left , right.Right ) && check(left.Right , right.Left )
}