算法训练营笔记day15|102. 二叉树的层序遍历、226. 翻转二叉树、101. 对称二叉树

102. 二叉树的层序遍历

题目连接

笔记

一次循环遍历一层,每次循环用一个size记录这一层的节点个数。

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        queue<TreeNode*> que;
        if (root == NULL) return result;
        que.push(root);
        while (!que.empty()) {
            int size = que.size();
            vector<int> vec;
            for (int i = 0; i < size; i++) {
                TreeNode* cur = que.front();
                vec.push_back(cur->val);
                if (cur->left) que.push(cur->left);
                if (cur->right) que.push(cur->right);
                que.pop();
            }
            result.push_back(vec);
        }
        return result;
    }
};

226. 翻转二叉树

题目连接

笔记

用一个先序遍历的递归,每次更换左右子树。

class Solution {
public:
    void reverseTree(TreeNode* node) {
        if (node == NULL) return;
        TreeNode* tem = node->left;
        node->left = node->right;
        node->right = tem;
        reverseTree(node->left);
        reverseTree(node->right);
    }
    TreeNode* invertTree(TreeNode* root) {
        reverseTree(root);
        return root;
    }
};

101. 对称二叉树

题目连接

笔记

用先序或者后序遍历,每次判断左右节点的值是否相等,再判断左节点的左孩子和右节点的右孩子是否相等…

class Solution {
public:
    bool issymmetric(TreeNode* left, TreeNode* right) {
        if (left == NULL && right == NULL) return true;
        if (left == NULL || right == NULL) return false;
        bool flag;
        flag = issymmetric(left->left, right->right);
        if (flag == false) return false;
        flag = issymmetric(left->right, right->left);
        if (flag == false) return false;
        if (left->val != right->val) return false;
        return true;
    }
    bool isSymmetric(TreeNode* root) {
        if (root == NULL) return true;
        return issymmetric(root->left, root->right);
    }
};

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