对称的二叉树
-
首先判断当前二叉树是否为空,若是,则直接返回true;
否则,进行比较其左右子树是否为镜像
首先判断当前左右结点是否存在空,若都为空,则返回true;否则返回false
然后判断当前左右节点的值是否相等
最后递归比较左子树的左孩子与右子树的右孩子以及左子树的右孩子与右子树的左孩子
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null)
return true;
return dfs(root.left,root.right);
}
private boolean dfs(TreeNode left, TreeNode right) {
if (left == null || right == null)
return (left == null) && (right == null);
if (left.val != right.val)
return false;
return dfs(left.left,right.right) && dfs(left.right,right.left);
}
}