Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1 2 3 4 5
| 1 / \ 2 2 / \ / \ 3 4 4 3
|
But the following [1,2,2,null,3,null,3] is not:
O(n) time, O(n) space DFS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) return true; return isMirror(root.left, root.right); } public boolean isMirror(TreeNode left, TreeNode right) { if (left == null || right == null) return left == right; return left.val == right.val && isMirror(left.left, right.right) && isMirror(left.right, right.left); } }
|
O(n) time O(n) space BFS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) return true; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root.left); queue.add(root.right); while (! queue.isEmpty()) { TreeNode n1 = queue.poll(); TreeNode n2 = queue.poll(); if (n1 == null || n2 == null ) { if (n1 != n2) return false; } else { if (n1.val != n2.val) { return false; } queue.add(n1.left); queue.add(n2.right); queue.add(n1.right); queue.add(n2.left); } } return true; } }
|