Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
题目的意思是让我们判断一颗树是否为对称树,我们需要判断root的左右节点是否相同,再去判断root的左节点的左节点与root的右节点的右节点是否相同,root的左节点的右节点和root的右节点的左节点是否相同。所以需要另外写一个递归函数,递归的终止条件是搜索到某一节点的左子树或右子树为空,如果只是左子树为空(右子树非空),再去调用递归函数直到搜索到叶子节点。代码如下:
public boolean isSymmetric(TreeNode root) {
if(root==null){return true;}
return function(root.left,root.right);
}
public boolean function(TreeNode left,TreeNode right){
if(left==null||right==null){return left==right;}
if(left.val!=right.val){return false;}
else{return function(left.left,right.right)&&function(left.right,right.left);}
}