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 3But the following is not: 1 / 2 2 \ 3 3Note:Bonus points if you could solve it both recursively and iteratively.
Difficulty: 82. This is the question of the tree, which is essentially a tree traversal. The Traversal method does not matter here. You only need to compare the corresponding nodes. The symmetry of a tree is to see whether the Left and Right Subtrees are symmetric. One sentence is left, right, and left, and the nodes are symmetric and equal. Asymmetric conditions include the following: (1) empty on the left and empty on the right; (2) empty on the left and empty on the right; (3) the left value is not equal to the right value. You can determine the time duration based on these conditions.
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 public class Solution {11 public boolean isSymmetric(TreeNode root) {12 if (root == null) return true;13 return check(root.left, root.right);14 }15 16 public boolean check(TreeNode node1, TreeNode node2) {17 if (node1 == null && node2 == null) return true;18 else if (node1 == null && node2 != null) return false;19 else if (node1 != null && node2 == null) return false;20 else if (node1.val != node2.val) return false;21 return check(node1.left, node2.right) && check(node1.right, node2.left);22 }23 }
For the iterative method, refer to the solution on the Internet:
public boolean isSymmetric(TreeNode root) { if(root == null) return true; if(root.left == null && root.right == null) return true; if(root.left == null || root.right == null) return false; LinkedList<TreeNode> q1 = new LinkedList<TreeNode>(); LinkedList<TreeNode> q2 = new LinkedList<TreeNode>(); q1.add(root.left); q2.add(root.right); while(!q1.isEmpty() && !q2.isEmpty()) { TreeNode n1 = q1.poll(); TreeNode n2 = q2.poll(); if(n1.val != n2.val) return false; if(n1.left == null && n2.right != null || n1.left != null && n2.right == null) return false; if(n1.right == null && n2.left != null || n1.right != null && n2.left == null) return false; if(n1.left != null && n2.right != null) { q1.add(n1.left); q2.add(n2.right); } if(n1.right != null && n2.left != null) { q1.add(n1.right); q2.add(n2.left); } } return true;}
Leetcode: Invalid Ric tree