问题描述(原题链接)
给你一个二叉树的根节点 root , 检查它是否轴对称。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
//思路:直接验证左边是否等于右边
return search(root,root);
}
private boolean search(TreeNode p,TreeNode q){
if(p==null && q==null)
return true;
if(p==null || q==null)
return false;
return p.val==q.val && search(p.left,q.right) && search(p.right,q.left);
}
}