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

     

  • 相关阅读:
    oracle常用sql语句
    Oracle存储过程基本语法介绍
    优美的代码:do...while(0)
    半同步半异步线程池
    C11线程管理:异步操作
    C11线程管理:原子变量&单调函数
    C11线程管理:条件变量
    C11线程管理:互斥锁
    C11线程管理:线程创建
    C11关键字&字面值改善
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4682523.html
Copyright © 2020-2023  润新知