L101. Symmetric Tree
binary tree
Problem:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1
/ \
2 2
\ \
3 3
Solution:
if it is null, it is mirrored, otherwise , compare left and right's value.
public boolean isSymmetric(TreeNode root){
return root == null ? true : isMirror(root.left, root.right);
}
private boolean isMirror(TreeNode left, TreeNode right){
if(left == null && right == null) return true;
if(left == null || right == null) return false;
if(left.val != right.val) return false;
return isMirror(left.left, right.right) && isMirror(left.right, right.left);
}
Iteration with two stack
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
if (root.left == null && root.right == null) return true;
if (root.left == null || root.right == null) return false;
// children are not null
Stack<TreeNode> stack = new Stack<>();
stack.push(root.left);
stack.push(root.right);
while (stack.size() > 0) {
TreeNode t1 = stack.pop();
TreeNode t2 = stack.pop();
// null check
if (t1 == null && t2 == null) continue;
if (t1 == null || t2 == null) return false;
// value check
if (t1.val != t2.val) return false;
// push children
stack.push(t1.right); stack.push(t2.left); // could be null
stack.push(t1.left); stack.push(t2.right);
}
return true;
}
Last updated
Was this helpful?