• 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. }








  • 相关阅读:
    二叉树
    队列
    python3使用pdfminer3k解析pdf文件
    得到手机版新闻解析
    python连接redis并插入url
    Python使用requirements.txt安装类库
    (1366, "Incorrect string value: '\xF3\xB0\x84\xBC</...' for column 'content' at row 1")
    mysql中Incorrect string value乱码问题解决方案
    mysql命令
    requests ip代理池单ip和多ip设置方式
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/74acf933880d0f5f01455f39d66e9a15.html
Copyright © 2020-2023  润新知