/**
* 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 {
Queue<TreeNode> Q = new Queue<TreeNode>(); private List<string> GetFloorString()
{
var floor = new List<string>(); var count = ;
while (Q.Count > )
{
var n = Q.Dequeue();
if (n.left != null)
{
floor.Add(n.left.val.ToString());
Q.Enqueue(n.left);
count++;
}
else
{
floor.Add("x");
}
if (n.right != null)
{
floor.Add(n.right.val.ToString());
Q.Enqueue(n.right);
count++;
}
else
{
floor.Add("x");
}
}
return floor;
} public bool IsSymmetric(TreeNode root)
{
if (root == null)
{
return true;
}
else
{
Q.Enqueue(root);
var str = GetFloorString(); int index = ;//起始索引
var xcount = ;
//len长度
for (int len = ; index + len <= str.Count && len > ; len = * (len - xcount))
{
xcount = ;
var l = new List<string>();//str.Substring(index, len);
for (int i = index; i < index + len; i++)
{
l.Add(str[i]);
} var halflen = len / ;
var l1 = new List<string>();
for (int i = ; i < halflen; i++)
{
l1.Add(l[i]);
}
//var s2 = s.Substring(halflen, halflen);
var l2 = new List<string>();
for (int i = halflen; i < halflen + halflen; i++)
{
l2.Add(l[i]);
} l2.Reverse(); var s1 = "";
var s2 = ""; for (int i = ; i < l1.Count; i++)
{
s1 += l1[i];
} for (int i = ; i < l2.Count; i++)
{
s2 += l2[i];
} if (s1 != s2)
{
return false;
} foreach (var c in l)
{
if (c == "x")
{
xcount++;
}
} index = index + len;
} return true;
}
}
}
https://leetcode.com/problems/symmetric-tree/#/description
补充一个python的实现:
class Solution:
def isSymmetric(self, root: 'TreeNode') -> 'bool':
if root == None:
return True
return self.isSymmetric2(root.left,root.right) def isSymmetric2(self,left,right):
if left == None and right == None:
return True
if left == None or right == None:
return False
if left.val != right.val:
return False
return self.isSymmetric2(left.left,right.right) and self.isSymmetric2(left.right,right.left)