Question
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
Note:
Bonus points if you could solve it both recursively and iteratively.
Thinking
此題可以用深度優先搜尋法(Depth-first Search),採recursive的方式;或是廣度優先搜尋法(Breadth-first Search),利用Queue以iterative的方式處理
My C# Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public bool IsSymmetric(TreeNode root) {
return (root != null)
? IsLeftEqualRight(root.left, root.right)
: true;
}
private bool IsLeftEqualRight(TreeNode left, TreeNode right)
{
if (left == null || right == null) return left == right;
return (left.val == right.val)
? IsLeftEqualRight(left.right, right.left)
&& IsLeftEqualRight(left.left, right.right)
: false;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public bool IsSymmetric(TreeNode root) {
if (root == null) return true;
var queue = new Queue<TreeNode>();
queue.Enqueue(root.left);
queue.Enqueue(root.right);
while(queue.Count > 0)
{
var right = queue.Dequeue();
var left = queue.Dequeue();
if (right == null && left == null) continue;
if (right == null
|| left == null
|| right.val != left.val) return false;
queue.Enqueue(left.left);
queue.Enqueue(right.right);
queue.Enqueue(left.right);
queue.Enqueue(right.left);
}
return true;
}
}