Bonus points if you could solve it both recursively and iteratively.
Version #2 Iteration
一个很神的Level order traversal
每次还是按Mirror的顺序往queue里面加TreeNode就好了
12.65 %
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
Queue<TreeNode> que = new LinkedList<>();
que.offer(root.left);
que.offer(root.right);
TreeNode leftNode;
TreeNode rightNode;
while (que.size() > 1) {
leftNode = que.poll();
rightNode = que.poll();
if (leftNode == null && rightNode == null) continue;
if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) return false;
que.offer(leftNode.left);
que.offer(rightNode.right);
que.offer(leftNode.right);
que.offer(rightNode.left);
}
return true;
}
}
Version #1 Recursion
二刷
22.55 %
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return isSymmetric(root.left, root.right);
}
private boolean isSymmetric(TreeNode leftRoot, TreeNode rightRoot) {
if (leftRoot == null && rightRoot == null) return true;
if (leftRoot == null || rightRoot == null) return false;
if (leftRoot.val != rightRoot.val) return false;
return isSymmetric(leftRoot.left, rightRoot.right) && isSymmetric(leftRoot.right, rightRoot.left);
}
}
一刷
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
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;
} else if (left == null || right == null) {
return false;
} else if (left.val != right.val) {
return false;
} else {
//System.out.println(left.val + " " + right.val);
return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
}
}
}
No comments:
Post a Comment