原文链接:101. 对称二叉树 - 力扣(LeetCode)
给你一个二叉树的根节点 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
解题思路
1、只要有一边为空,一边不为空,就返回false
2、若左子树的左孩子和右子数的右孩子不相等或左子树的右孩子和右子数的左孩子不相等,就返回false
(1)递归
- /**
- * 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) return true;
- return isTrue(root.left,root.right);
- }
- public boolean isTrue(TreeNode node1,TreeNode node2){
- if(node1==null && node2==null)return true;
- if(node1==null || node2==null || node1.val != node2.val)return false;
- return isTrue(node1.left,node2.right)&&isTrue(node1.right,node2.left);
- }
- }
(2)迭代
- /**
- * 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 check(root, root);
- }
- public boolean check(TreeNode m, TreeNode n) {
- Queue
queue = new LinkedList(); - queue.offer(m);
- queue.offer(n);
- while (!queue.isEmpty()) {
- m = queue.poll();
- n = queue.poll();
- if(m==null && n==null){
- continue;
- }
- if((m==null||n==null) || (m.val!=n.val)){
- return false;
- }
- queue.offer(m.left);
- queue.offer(n.right);
- queue.offer(m.right);
- queue.offer(n.left);
- }
- return true;
- }
- }
-