zoukankan      html  css  js  c++  java
  • Symmetric Tree <LeetCode>

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

    For example, this binary tree is symmetric:

        1
       / 
      2   2
     /  / 
    3  4 4  3
    

    But the following is not:

        1
       / 
      2   2
          
       3    3


    思路:首先把想到用递归分别遍历左右子树,不同的时,遍历左子树时,先遍历根节点,然后是左孩子,最后右孩子;遍历右子树时,县遍历根节点,然后是右孩子,最后是左孩子,每遍历到一个节点进行比较,是否相同,代码如下://没有优化

     1 /**
     2  * Definition for binary tree
     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)  return true;
    14         TreeNode *rootl;
    15         TreeNode *rootr;
    16         rootl=root->left;
    17         rootr=root->right;
    18         return isSame(rootl,rootr);
    19     }
    20     
    21     bool isSame(TreeNode *rootl,TreeNode *rootr)
    22     {
    23         if(rootl==NULL||rootr==NULL)
    24         {
    25             if(rootl!=NULL||rootr!=NULL)
    26             {
    27                 return false;
    28             }
    29             else return true;
    30         }
    31         
    32         if(rootl->val!=rootr->val)  return false;
    33         else
    34         {
    35             if(isSame(rootl->left,rootr->right))
    36             {
    37                 if(isSame(rootl->right,rootr->left))
    38                 {
    39                     return true;
    40                 }
    41                 else return false;
    42             }
    43             else return false;
    44         }
    45         
    46     }
    47 };
  • 相关阅读:
    信息安全系统设计基础第十二周学习总结
    day07-流程控制之while循环
    day07-深浅拷贝
    第一次小测
    day05-与用户交互与运算符
    day05学习笔记-垃圾回收机制
    day04学习笔记-变量
    day03-python-学习笔记
    P4323-[JSOI2016]独特的树叶【换根dp,树哈希】
    CF990G-GCD Counting【dfs】
  • 原文地址:https://www.cnblogs.com/sqxw/p/3952962.html
Copyright © 2011-2022 走看看