对称二叉树

题目:

请实现一个函数,用来判断一颗二叉树是不是对称的。如果一颗二叉树和它的镜像是一样的,那么它就是对称的。

解答:

 1 public class Solution {
 2 
 3     public static boolean isSymmetrical(TreeNode root) {
 4         return isSymmetrical(root, root);
 5     }
 6 
 7     private static boolean isSymmetrical(TreeNode root1, TreeNode root2) {
 8         if(root1 == null && root2 == null) {
 9             return true;
10         }
11 
12         if(root1 == null || root2 == null) {
13             return false;
14         }
15 
16         if(root1.val != root2.val) {
17             return false;
18         }
19 
20         return isSymmetrical(root1.left, root2.right) && isSymmetrical(root1.right, root2.left);
21     }
22 }

 

原文地址:https://www.cnblogs.com/wylwyl/p/10462061.html