Binary Search:
note that: "Check the left.left equal to the right.right."
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition of TreeNode: | |
* public class TreeNode { | |
* public int val; | |
* public TreeNode left, right; | |
* public TreeNode(int val) { | |
* this.val = val; | |
* this.left = this.right = null; | |
* } | |
* } | |
*/ | |
// Approach #1 - Recursion - T O(#OfNodes). | |
public class Solution { | |
/** | |
* @param root: root of the given tree | |
* @return: whether it is a mirror of itself | |
*/ | |
public boolean isSymmetric(TreeNode root) { | |
// Write your code here | |
if (root == null) { | |
return true; | |
} | |
return isSymmetric(root.left, root.right); | |
} | |
private boolean isSymmetric(TreeNode left, TreeNode right) { | |
if (left == null && right == null) { | |
return true; | |
} | |
if (left == null || right == null) { | |
return false; | |
} | |
return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); | |
} | |
} |
No comments:
Post a Comment