[二叉树专题]二叉树的层次遍历|翻转二叉树|对称二叉树

 一、层次遍历


class Solution {
public:
    vector> levelOrder(TreeNode* root) {
        vector> result;
        queue q;
        if (root == nullptr)
            return result;
        q.push(root);
        while (!q.empty()) {
            vector n;
            int size = q.size();
            while (size--) {
                TreeNode* tmp = q.front();
                n.push_back(tmp->val);
                q.pop();
                if (tmp->left)
                    q.push(tmp->left);
                if (tmp->right)
                    q.push(tmp->right);
            }
            result.push_back(n);
        }

        return result;
    }
};

 二、翻转二叉树


class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
     if(root==nullptr)
     return nullptr;
     mirrorTree(root->left);
     mirrorTree(root->right);
     swap(root->left,root->right);
     return root;
    }
};

三、对称二叉树


class Solution {
public:
    bool compare(TreeNode* left, TreeNode* right) {
        if (left == NULL && right != NULL)
            return false;
        else if (left != NULL && right == NULL)
            return false;
        else if (left == NULL && right == NULL)
            return true;
        else if (left->val != right->val)
            return false;
        bool outside = compare(left->left, right->right);
        bool inside = compare(left->right, right->left);

        return outside && inside;
    }
    bool isSymmetric(TreeNode* root) {
        if (root == NULL)
            return true;
        return compare(root->left, root->right);
    }
};

你可能感兴趣的:(算法,数据结构,leetcode)