Loading

【算法训练营day15】LeetCode102. 二叉树的层序遍历 LeetCode226. 翻转二叉树 LeetCode101. 对称二叉树

LeetCode102. 二叉树的层序遍历

题目链接:102. 二叉树的层序遍历

初次尝试

直接看题解学习思路。

看完代码随想录后的想法

迭代法层序遍历。

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> que;
        vector<vector<int>> ans;
        if (root != NULL) que.push(root);

        while (!que.empty()) {
            int size = que.size();
            vector<int> vec;
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                vec.push_back(node -> val);
                if (node -> left) que.push(node -> left);
                if (node -> right) que.push(node -> right);
            }
            ans.push_back(vec);
        }

        return ans;
    }
};

递归法层序遍历。

class Solution {
public:
    void order(TreeNode* cur, vector<vector<int>>& result, int depth)
    {
        if (cur == nullptr) return;
        if (result.size() == depth) result.push_back(vector<int>());
        result[depth].push_back(cur->val);
        order(cur->left, result, depth + 1);
        order(cur->right, result, depth + 1);
    }
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        int depth = 0;
        order(root, result, depth);
        return result;
    }
};

LeetCode226. 翻转二叉树

题目链接:226. 翻转二叉树

初次尝试

直接看题解学习思路。

看完代码随想录后的想法

递归前序遍历将节点处理语句ans.push_back(node -> val)改成swap(root -> left, root -> right)即可,递归后序遍历也可以,但是递归中序遍历不行,因为使用递归中序遍历,某些节点的孩子会翻转两次。但是统一迭代中序遍历是可以的,因为统一迭代中序遍历是用栈而不是用指针来遍历的。

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

LeetCode101. 对称二叉树

题目链接:101. 对称二叉树

初次尝试

直接看题解学习思路。

看完代码随想录后的想法

这道题的思路本质上是分别遍历根节点的左右子树,镜像的对比左右子树的节点是否相等,因为需要镜像的遍历,所以左右子树的遍历顺序是不一样的,左子树是左右中,右子树是右左中,但都是类后序遍历。递归法代码较为简洁,本题同时还可以用迭代法解,思路如下。

通过一个容器来成对的存放我们要比较的元素,知道这一本质之后就发现,用队列,用栈,甚至用数组,都是可以的。

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 false;
        return compare(root -> left, root -> right);
    }
};
posted @ 2022-11-14 10:32  BarcelonaTong  阅读(26)  评论(0)    收藏  举报