zoukankan      html  css  js  c++  java
  • 对称的二叉树

    对称的二叉树

    题目描述

    请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

    class Solution {
    public:
        
        bool isSymmetrical(TreeNode *pRoot1, TreeNode *pRoot2) {
            if ((nullptr == pRoot1) && (nullptr == pRoot2)) {
                return true;
            }
            if ((nullptr == pRoot1) || (nullptr == pRoot2)) {
                return false;
            }
            if (pRoot1->val != pRoot2->val) {
                return false;
            }
            return isSymmetrical(pRoot1->left, pRoot2->right)
                && isSymmetrical(pRoot1->right, pRoot2->left);
        }
        
        bool isSymmetrical(TreeNode* pRoot)
        {
            return isSymmetrical(pRoot, pRoot);
        }
    
    };
    

    原来想利用中序左右对称来做, 后来发现不可行, 因为当树的元素对应值都相同时失效

    class Solution {
    public:
        
        vector<int> vt;
        
        void midOrder(TreeNode *pRoot) {
            if (nullptr == pRoot) {
                return;
            }
            if (pRoot->left != nullptr)
            midOrder(pRoot->left);
            
            vt.push_back(pRoot->val);
            if (pRoot->right != nullptr)
            midOrder(pRoot->right);
        }
        
        bool isSymmetrical(TreeNode* pRoot)
        {
            midOrder(pRoot);
            // 中间节点的下一位置
            int high = vt.size() - 1;
            int low = 0;
            
            while (low < high) {
                if (vt[high--] != vt[low++]) {
                    return false;
                }
            }
            
            return true;
        }
    
    };
    
    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };
    */
    
  • 相关阅读:
    web.xml模板
    log4j.properties模板
    springmvc-config.xml模板
    applicationContext.xml配置druid连接池
    mybatis-config.xml模板
    mapper.xml模板
    Servlet基础认识
    单例模式的懒汉饿汉
    霜降小悟
    忙闲有致
  • 原文地址:https://www.cnblogs.com/hesper/p/10502285.html
Copyright © 2011-2022 走看看