For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3But the following is not:
1 / \ 2 2 \ \ 3 3Note:
Bonus points if you could solve it both recursively and iteratively.
Confused what
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.---
Solution: Recurse check for equality, except that we compare the left.left child with the right.right child, and the right.left child with the left.right child.
Algorithm 1: Recursive (easier)
/**
* 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 == right) return true;
if (left == null || right == null) return false;
if (left.val != right.val) return false;
return isSymmetric(left.left, right.right) && isSymmetric(right.left, left.right);
}
}
Algorithm 2: Iterative (harder)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private static class TreeNodePair {
private TreeNode node1;
private TreeNode node2;
private TreeNodePair(TreeNode node1, TreeNode node2) {
this.node1 = node1;
this.node2 = node2;
}
}
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
Stack stack = new Stack<>();
stack.add(new TreeNodePair(root.left, root.right));
do {
TreeNodePair pair = stack.pop();
if (pair.node1 == pair.node2) continue;
if (pair.node1 == null || pair.node2 == null) return false;
if (pair.node1.val != pair.node2.val) return false;
stack.add(new TreeNodePair(pair.node1.left, pair.node2.right));
stack.add(new TreeNodePair(pair.node2.left, pair.node1.right));
} while (!stack.isEmpty());
return true;
}
}
No comments:
Post a Comment