首页 > 代码库 > 101. Symmetric Tree 二叉树是否对称

101. Symmetric Tree 二叉树是否对称

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.

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left;
  6. * public TreeNode right;
  7. * public TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public bool IsSymmetric(TreeNode root) {
  12. if (root == null) return true;
  13. Queue<TreeNode> queue = new Queue<TreeNode>();
  14. queue.Enqueue(root);
  15. while (queue.Count > 0) {
  16. int count = queue.Count;
  17. List<int?> nextLevel = new List<int?>();
  18. for (int i = 0; i < count; i++) {
  19. TreeNode curNode = queue.Dequeue();
  20. if (curNode.left != null) {
  21. queue.Enqueue(curNode.left);
  22. nextLevel.Add(curNode.left.val);
  23. } else {
  24. nextLevel.Add(null);
  25. }
  26. if (curNode.right != null) {
  27. queue.Enqueue(curNode.right);
  28. nextLevel.Add(curNode.right.val);
  29. } else {
  30. nextLevel.Add(null);
  31. }
  32. }
  33. if (!LevelIsSymmetric(nextLevel)){
  34. return false;
  35. }
  36. }
  37. return true;
  38. }
  39. public bool LevelIsSymmetric(List<int?> list) {
  40. int left = 0;
  41. int right = list.Count - 1;
  42. while (right > left) {
  43. if (list[left++] != list[right--]) {
  44. return false;
  45. }
  46. }
  47. return true;
  48. }
  49. }






null


101. Symmetric Tree 二叉树是否对称