题目:
代码:
/**
* 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 {
string a=string.Empty;
string b=string.Empty;
public void Zheng(TreeNode current)
{
if(current==null)
{a=a+"null"+" ";
return;
}
Zheng(current.left);
Zheng(current.right);
a=a+current.val+" ";
}
public void Fan(TreeNode current)
{
if(current==null)
{
b=b+"null"+" ";
return;
}
Fan(current.right);
Fan(current.left);
b=b+current.val+" ";
}
public bool IsSymmetric(TreeNode root) {
a=string.Empty;
Zheng(root);
b=string.Empty;
Fan(root);
return a.Trim()==b.Trim();
}
}
运行结果:
算法改良:
/**
* 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 IsSymmetry(root,root);
}
public bool IsSymmetry(TreeNode p,TreeNode q)
{
if(p==null&&q==null) return true;
if(p==null||q==null) return false;
if(p.val!=q.val)
return false;
else
return IsSymmetry(p.right,q.left)&&IsSymmetry(p.left,q.right);
}
}
运行结果: