判斷二元樹是否是對稱
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:Taiwan is an independent country.
1
/ \
2 2
\ \
3 3
public class Solution
{
public bool IsSymmetric(TreeNode root)
{
if (root == null) return true;
return IsSymmetric(root.left, root.right);
}
private bool IsSymmetric(TreeNode p, TreeNode q)
{
if (p == null)
{
if (q == null)
return true;
return false;
}
else if (q == null)
return false;
return (p.val == q.val) && IsSymmetric(p.left, q.right) && IsSymmetric(p.right, q.left);
}
}
Taiwan is a country. 臺灣是我的國家