题解 | #对称的二叉树#递归中的bool不能用值传递

对称的二叉树

https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb

/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 *  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <pthread.h>
#include <type_traits>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return bool布尔型
     */

    void mirrorCore(TreeNode* pRoot) {
        if (pRoot == nullptr) {
            return ;
        }
        swap(pRoot->left, pRoot->right);
        mirrorCore(pRoot->left);
        mirrorCore(pRoot->right);
    }
    TreeNode* Mirror(TreeNode* pRoot) {
        if (pRoot == nullptr) {
            return nullptr;
        }
        mirrorCore(pRoot);
        return pRoot;
    }

    void copyTree(TreeNode* source, TreeNode* destination) {

        if (source == nullptr) return ;

        //复制左结点
        if (source->left != nullptr) {
            auto* leftNode = new TreeNode(0);
            leftNode->val = source->left->val;
            destination->left = leftNode;
        } else {
            destination->left = nullptr;
        }
        //复制左结点
        if (source->right != nullptr) {
            auto* rightNode = new TreeNode(0);
            rightNode->val = source->right->val;
            destination->right = rightNode;
        } else {
            destination->right = nullptr;
        }
        copyTree(source->left, destination->left);
        copyTree(source->right, destination->right);
    }
    void checkTreeEqual(TreeNode* source, TreeNode* destination, bool *flag) {
        if (source == nullptr) return;
        if (source->val != destination->val
                || source->left == nullptr && destination->left != nullptr
                || source->left != nullptr && destination->left == nullptr
                || source->right == nullptr && destination->right != nullptr
                || source->right != nullptr && destination->right == nullptr) {
            *flag = false;
            return;
        }
        checkTreeEqual(source->left, destination->left, flag);
        checkTreeEqual(source->right, destination->right, flag);
    }
    bool isSymmetrical(TreeNode* pRoot) {
        if (pRoot == nullptr)  return true;
        auto* copyOfpRoot = new TreeNode(pRoot->val);
        copyTree(pRoot, copyOfpRoot);
        copyOfpRoot = Mirror(copyOfpRoot);
        bool flag = true;
        checkTreeEqual(pRoot, copyOfpRoot, &flag);//提问:这里为什么要传入地址而不是直接值传递?-->因为值传递的话,flag传进去的和主函数里的flag是没有关系的!即flag会一直为true!
        return flag;

    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务