Symmetric tree
Given a binary tree, check whether it is a mirror of itself (ie, shortric around its center ).
For example, this binary tree is unsupported Ric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you cocould solve it both recursively and iteratively.
Confused what"{1,#,2,3}"
Means? > Read more on how binary tree is serialized on OJ.
[Analysis 1-original] uses a recursive solution. You can check the reference for the solution.
Reference: https://oj.leetcode.com/discuss/456/recusive-solution-symmetric-optimal-solution-inordertraversal
public static boolean isSymmetric(TreeNode root) { if(root==null) return true; return checkIsSymmetric(root.left,root.right); } private static boolean checkIsSymmetric(TreeNode leftNode,TreeNode rightNode) { if(leftNode==null&&rightNode==null) return true; if((leftNode!=null&&rightNode==null)||(leftNode==null&&rightNode!=null)) return false; if(leftNode.val!=rightNode.val) return false; return checkIsSymmetric(leftNode.left,rightNode.right)&&checkIsSymmetric(leftNode.right,rightNode.left);}
[Analysis 2-non-original] Use stack to stack left and right, and then compare each layer.
Reference: https://oj.leetcode.com/discuss/456/recusive-solution-symmetric-optimal-solution-inordertraversal
public boolean isSymmetric(TreeNode root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if (root == null) return true; Stack<TreeNode> s1 = new Stack<TreeNode>(); Stack<TreeNode> s2 = new Stack<TreeNode>(); s1.push(root.left); s2.push(root.right); while (!s1.empty() && !s2.empty()) { TreeNode n1 = s1.pop(); TreeNode n2 = s2.pop(); if (n1 == null && n2 == null) continue; if (n1 == null || n2 == null) return false; if (n1.val != n2.val) return false; s1.push(n1.left); s2.push(n2.right); s1.push(n1.right); s2.push(n2.left); } return true; }
[Leetcode topic record-11] Determining whether a binary tree is an image (symmetric)