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.confused whatSolution1: recursion"{1,#,2,3}"
means?
Run time complexity is O(n), space complexity is stack space O(logn).
/** * Definition for binary tree * 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 helper(root.left, root.right); } public boolean helper(TreeNode left, TreeNode right) { if(left == null && right == null) return true; if(left == null || right == null) return false; if(left.val != right.val) return false; return helper(left.right, right.left) && helper(left.left, right.right); } }Solution2: iterative
用两个queue来保存左右节点,一层一层遍历。
Run time complexity is O(n), space complexity is O(n).
/** * Definition for binary tree * 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; if(root.left == null && root.right == null) return true; if(root.left == null || root.right == null) return false; LinkedListqueue1 = new LinkedList (); LinkedList queue2 = new LinkedList (); queue1.add(root.left); queue2.add(root.right); while(!queue1.isEmpty() && !queue2.isEmpty()) { TreeNode curL = queue1.poll(); TreeNode curR = queue2.poll(); if(curL.left == null && curR.right != null || curL.left != null && curR.right == null) return false; if(curL.right == null && curR.left != null || curL.right != null && curR.left == null) return false; if(curL.val != curR.val) return false; if(curL.left != null && curR.right != null) { queue1.add(curL.left); queue2.add(curR.right); } if(curL.right != null && curR.left != null) { queue1.add(curL.right); queue2.add(curR.left); } } return true; } }