/** * 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 = 0; while (Q.Count > 0) { 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 = 0;//起始索引 var xcount = 0; //len长度 for (int len = 2; index + len <= str.Count && len > 0; len = 2 * (len - xcount)) { xcount = 0; var l = new List<string>();//str.Substring(index, len); for (int i = index; i < index + len; i++) { l.Add(str[i]); } var halflen = len / 2; var l1 = new List<string>(); for (int i = 0; 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 = 0; i < l1.Count; i++) { s1 += l1[i]; } for (int i = 0; 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的实现:
1 class Solution: 2 def isSymmetric(self, root: 'TreeNode') -> 'bool': 3 if root == None: 4 return True 5 return self.isSymmetric2(root.left,root.right) 6 7 def isSymmetric2(self,left,right): 8 if left == None and right == None: 9 return True 10 if left == None or right == None: 11 return False 12 if left.val != right.val: 13 return False 14 return self.isSymmetric2(left.left,right.right) and self.isSymmetric2(left.right,right.left)
Java版本:
1 class Solution { 2 public boolean isSymmetric(TreeNode root) { 3 if(root == null){ 4 return true; 5 }else{ 6 return sameTree(root.left,root.right); 7 } 8 } 9 10 public boolean sameTree(TreeNode left,TreeNode right){ 11 if(left == null && right == null){ 12 return true; 13 }else if(left != null && right == null){ 14 return false; 15 }else if(left == null && right != null){ 16 return false; 17 }else{ 18 if(left.val != right.val){ 19 return false; 20 }else{ 21 return sameTree(left.left,right.right) && sameTree(left.right,right.left); 22 } 23 } 24 } 25 }