问题描述:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Note:
Bonus points if you could solve it both recursively and iteratively.
解题思路:
递归的方法,每次递归的调用判断左子树、右子树是否对称相等
/**
* 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;//根节点为空,返回true
}else {
return isSymmetric(root.left, root.right);
}
}
public boolean isSymmetric(TreeNode pleft, TreeNode pright) {
if(pleft == null && pright == null) {
return true;//说明只有一个根节点,返回true
}
if(pleft == null || pright == null) {
return false;//一个子树为空,另一个子树不为空,返回false
}
//都不为空的情况下判断是否相等
if(pleft.val != pright.val) {
return false;
}
//继续判断左子树与右子树是否对称相等
return isSymmetric(pleft.left, pright.right)&&isSymmetric(pleft.right, pright.left);
}
}