Skip to content

Instantly share code, notes, and snippets.

@daifu
Created April 26, 2013 16:49
Show Gist options
  • Save daifu/5468687 to your computer and use it in GitHub Desktop.
Save daifu/5468687 to your computer and use it in GitHub Desktop.
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
Algorithm:
This problem will be good for topdown approach from a tree
1. Check all the situation execpt when both value are same
2. Repeat the recusion for left and right
3. Return the value for left and right and left.val == right.val
*/
/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
if(root == null) return true;
return isSymmetricHelper(root.left, root.right);
}
public boolean isSymmetricHelper(TreeNode left, TreeNode right) {
if(left == null && right == null) return true;
if(left == null) return false;
if(right == null) return false;
if(left.val != right.val) return false;
boolean leftCheck = isSymmetricHelper(left.left, right.right);
boolean rightCheck = isSymmetricHelper(left.right, right.left);
return leftCheck && rightCheck && (left.val == right.val);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment