Symmetric Tree
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 3
But the following is not:
1 / \ 2 2 \ \ 3 3
The binary tree problems are always solved by recursion. We can figure the regular pattern out by observing the tree above.
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null)
return true;
return symmetric(root.left, root.right);
}
private boolean symmetric(TreeNode node1, TreeNode node2) {
if (node1 == null && node2 == null)
return true;
if (node1 == null || node2 == null)
return false;
return (node1.val == node2.val) && symmetric(node1.left, node2.right) && symmetric(node1.right, node2.left);
}
}