Saturday, July 3, 2021

LintCode 1360 · Symmetric Tree.java

Binary Search:
note that: "Check the left.left equal to the right.right."
/**
* 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