Given a binary tree, check if it is mirror-symmetrical. For example, a binary tree [ 1 , 2 , 2 , 3 , 4 , 4 , 3 ] is symmetric. 1 / \ 2 2 / \ / \ . 3 . 4 . 4 . 3 , but the following [ 1 , 2 , 2 , null , . 3 , null , . 3 ] is not a mirror image: 1 / \ 2 2 \ \ . 3 . 3
Thinking: binary tree with a height greater than 2 bar for example, which is the first example above, the left child node and the node as long as the right child of 1 is equal to 2, the left and right child nodes and the node point 2 of the children are equal, we believe that is a mirror, provided that nodes 1 and 2 sibling node;
Recursive achieve the following:
public static boolean isSymmetric(TreeNode root) { if(root == null) return true; return in(root.left,root.right); } //递归 public static boolean in(TreeNode l1,TreeNode l2){ if(l1 == null && l2 == null) return true; if(l1 == null || l2 == null) return false; return l1.val == l2.val && in(l1.left,l2.right) && in(l1.right,l2.left); }
Non-recursive as follows:
//迭代 public static boolean isSymm(TreeNode root){ if(root == null) return true; Queue<TreeNode> q = new LinkedList<>(); q.add(root); q.add(root); while (!q.isEmpty()) { TreeNode t1 = q.poll(); TreeNode t2 = q.poll(); if (t1 == null && t2 == null) continue; if (t1 == null || t2 == null) return false; if (t1.val != t2.val) return false; q.add(t1.left); q.add(t2.right); q.add(t1.right); q.add(t2.left); } return true; }