• 【Leetcode】对称二叉树


    递归法

    执行用时 :12 ms, 在所有 C++ 提交中击败了43.44%的用户
    内存消耗 :14.6 MB, 在所有 C++ 提交中击败了95.56%的用户
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if(root == NULL)
                return true;
            
            if( isMirror(root->left, root->right))
                return true;
            else
                return false;
        }
        
        bool isMirror(TreeNode* lc, TreeNode* rc) {
            if(lc == NULL && rc == NULL)
                return true;
            
            if(lc == NULL || rc == NULL)
                return false;
            else {
                if (lc->val == rc->val)
                    return (isMirror(lc->left, rc->right) && isMirror(lc->right, rc->left));
                else
                    return false;
            }
        }
    };

    时间复杂度:

    O(n),因为算法过程要遍历树的每一个节点,节点数量为n。

    空间复杂度:

    O(n),递归函数使用的栈空间与树的层数有关。如果树为线性结构,其层数为n,所以空间复杂度为O(n)

    迭代法

    执行用时 :12 ms, 在所有 C++ 提交中击败了43.52%的用户
    内存消耗 :14.8 MB, 在所有 C++ 提交中击败了81.46%的用户
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if(root == NULL)
                return true;
            
            queue< TreeNode* > q1;
            queue< TreeNode* > q2;
            
            q1.push(root->left);
            q2.push(root->right);
            
            while(q1.size()>0 && q2.size()>0) {
                TreeNode* n1 = q1.front();
                TreeNode* n2 = q2.front();
                q1.pop();
                q2.pop();
                
                if(n1 == NULL && n2 == NULL)
                    continue;
    
                if(n1 == NULL || n2 == NULL)
                    return false;
                
                if(n1->val == n2->val) {
                    q1.push(n1->left);
                    q2.push(n2->right);
                    q1.push(n1->right);
                    q2.push(n2->left);
                }
                else
                    return false;
            }
            return true;
        }
    };

    时间复杂度:

    O(n) 要遍历每一个节点;

    空间复杂度:

    搜索队列需要额外的空间。在最糟糕情况下,我们不得不向队列中插入 O(n)个结点(???)。因此,空间复杂度为 O(n)。

  • 相关阅读:
    mysql8 JDBC连接注意事项
    Flask上下文管理源码分析
    python基础学习day5
    python基础学习day4
    python基础学习day3
    python基础学习day2
    python基础学习day1
    简单的名片管理系统
    pycharm教程
    Python:知识目录
  • 原文地址:https://www.cnblogs.com/gdut-gordon/p/11445061.html
Copyright © 2020-2023  润新知