Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \3 3
分析:当判断两个父节点是否对称后,就可以判断这两个父节点的字节点是否对称。采用递归即可
import java.util.*; public class Solution { public boolean isSymmetric(TreeNode root) { if(root==null){ return true; } return check(root.left,root.right); } public boolean check(TreeNode leftNode,TreeNode rightNode){ if(leftNode==null&&rightNode==null){ return true; } if(leftNode==null||rightNode==null){ return false; } return leftNode.val==rightNode.val&&check(leftNode.left,rightNode.right)&&check(leftNode.right,rightNode.left); } }