给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false
提示:
- 树中节点数目在范围
[1, 1000]
内 -100 <= Node.val <= 100
进阶:你可以运用递归和迭代两种方法解决这个问题吗?
/*** 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) {if (root == null || (root.left == null && root.right == null)) {return true;} else if ((root.left == null && root.right != null) || (root.left != null && root.right == null)) {return false;} else if (root.left.val != root.right.val) {return false;} else {return cycleTree(root.left, root.right);}}public boolean cycleTree(TreeNode p, TreeNode q) {boolean flag = true;if (p.left == null && q.right == null && p.right == null && q.left == null) {return true;} else if ((p.left == null && q.right != null) || (p.right == null && q.left != null)) {return false;} else if ((q.left == null && p.right != null) || (q.right == null && p.left != null)) {return false;} else if (p.left == null && q.right == null && p.right != null && q.left != null) {if (p.right.val != q.left.val) {return false;} else {flag = cycleTree(p.right, q.left);}} else if (q.left == null && p.right == null && q.right != null && p.left != null) {if (q.right.val != p.left.val) {return false;} else {flag = cycleTree(p.left, q.right);}} else if (p.left.val != q.right.val || p.right.val != q.left.val) {return false;} else {flag = cycleTree(p.left, q.right);if (!flag) {return flag;}flag = cycleTree(p.right, q.left);}return flag;}
}