zoukankan      html  css  js  c++  java
  • Symmetric Tree

    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

    Note:
    Bonus points if you could solve it both recursively and iteratively.

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

     

    Analyse: the same as Same Tree

    1. Recursion

        Runtime: 8ms.

     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) return true;
    14         return symmetric(root->left, root->right);
    15     }
    16     bool symmetric(TreeNode* leftNode, TreeNode* rightNode){
    17         if(!leftNode && !rightNode) return true;
    18         if(!leftNode || !rightNode) return false;
    19         
    20         return leftNode->val == rightNode->val &&
    21                symmetric(leftNode->left, rightNode->right) &&
    22                symmetric(leftNode->right, rightNode->left);
    23     }
    24 };

    2. Iteration

        Runtime: 4ms.

     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) return true;
    14         stack<TreeNode* > stk;
    15         stk.push(root->left);
    16         stk.push(root->right);
    17         
    18         while(!stk.empty()){
    19             TreeNode* node1 = stk.top();
    20             stk.pop();
    21             TreeNode* node2 = stk.top();
    22             stk.pop();
    23             
    24             if(!node1 && !node2) continue;
    25             if(!node1 || !node2) return false;
    26             if(node1->val != node2->val) return false;
    27             
    28             stk.push(node1->left);
    29             stk.push(node2->right);
    30             stk.push(node1->right);
    31             stk.push(node2->left);
    32         }
    33         return true;
    34     }
    35 };

     

  • 相关阅读:
    生命周期-BeanPostProcessor-后置处理器
    生命周期-@PostConstruct&@PreDestroy
    生命周期-InitializingBean和DisposableBean
    异常安全
    inline函数
    bool类型
    函数重载与默认参数
    C++强制转换
    引用
    new/delete表达式
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4682523.html
Copyright © 2011-2022 走看看