• leetcode 101


    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  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     bool isSymmetric(TreeNode* root) {
    13         if(root == NULL)
    14         {
    15             return true;
    16         }
    17         return isSame(root->left, root->right);
    18     }
    19     bool isSame(TreeNode* left, TreeNode* right)
    20     {
    21         if(left == NULL && right == NULL)
    22         {
    23             return true;
    24         }
    25         else if(left == NULL)
    26         {
    27             return false;
    28         }
    29         else if(right == NULL)
    30         {
    31             return false;
    32         }
    33         
    34         if(left->val == right->val && left->left == NULL && left->right && right->right == NULL && right->left == NULL)
    35         {
    36             return true;
    37         }
    38         else if(left->val == right->val)
    39         {
    40             return isSame(left->left, right->right) && isSame(left->right, right->left);
    41         }
    42         else
    43         {
    44             return false;
    45         }
    46         
    47     }
    48 };
  • 相关阅读:
    马拉车算法【Manachar】
    AcWing算法进阶课 基础算法 启发式合并
    iframe嵌套跨域子页面变化高度自适应
    js数组中的每一项异步请求
    利用geo3d地图数据画地图上面的柱子
    地图上面加柱状图组
    antd-select选项位置偏移问题解决
    git
    React
    前端面试题
  • 原文地址:https://www.cnblogs.com/shellfishsplace/p/5864219.html
Copyright © 2020-2023  润新知