【算法与数据结构】226、LeetCode翻转二叉树

文章目录

  • 一、题目
  • 二、解法
  • 三、完整代码

所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解。

一、题目

【算法与数据结构】226、LeetCode翻转二叉树_第1张图片

二、解法

  思路分析:这道题的思路很简单,本质上就是遍历每一个节点,然后交换左右节点。我们可以用前中后遍历或者是层次遍历法来做,参考这两篇文章,【算法与数据结构】144、94、145LeetCode二叉树的前中后遍历(递归法、迭代法)和【算法和数据结构】102、LeetCode二叉树的层序遍历。交换函数可以用库函数也可以自己写一个my_sawp()函数。
  my_sawp()函数如下

void my_swap(TreeNode* &root) {
    TreeNode* node = root->left;
    root->left = root->right;
    root->right = node;
}

  迭代法前序遍历程序如下

class Solution1 {
public:
    // 迭代法,前序遍历
    TreeNode* invertTree(TreeNode* root) {
        stack<TreeNode*> st;
        if (root != NULL) st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();              // 中
            st.pop();
            swap(node->left, node->right);
            if (node->right) st.push(node->right);  // 右
            if (node->left) st.push(node->left);    // 左
        }
        return root;
    }
};

  前序遍历,统一代码风格迭代写法

class Solution2 {
public:
    // 前序遍历,统一代码风格迭代写法
    TreeNode* invertTree(TreeNode* root) {
        stack<TreeNode*> st;
        if (root != NULL) st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();
            if (node != NULL) {              
                st.pop();
                if (node->right) st.push(node->right);  // 右
                if (node->left) st.push(node->left);    // 左
                st.push(node);                          // 中
                st.push(NULL);
            }
            else {
                st.pop();
                node = st.top();
                st.pop();
                swap(node->left, node->right);
            }
        }
        return root;
    }
};

  递归法程序如下

class Solution3 {
public:
    // 递归法
    TreeNode* invertTree(TreeNode* root) {
        if (root == NULL) return root;
        swap(root->left, root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

  层序遍历法程序如下

class Solution4 {
public:
	// 层序遍历法
    TreeNode* invertTree(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        vector<vector<int>> result;
        while (!que.empty()) {
            int size = que.size();  // size必须固定, que.size()是不断变化的
            for (int i = 0; i < size; ++i) {
                TreeNode* node = que.front();
                swap(node->left, node->right);
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return root;
    }
};

三、完整代码

# include 
# include 
# include 
# include 
# include 
using namespace std;

// 树节点定义
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

void my_swap(TreeNode*& root) {
    TreeNode* node = root->left;
    root->left = root->right;
    root->right = node;
}

class Solution1 {
public:
    // 迭代法,前序遍历
    TreeNode* invertTree(TreeNode* root) {
        stack<TreeNode*> st;
        if (root != NULL) st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();              // 中
            st.pop();
            swap(node->left, node->right);
            if (node->right) st.push(node->right);  // 右
            if (node->left) st.push(node->left);    // 左
        }
        return root;
    }
};

class Solution2 {
public:
    // 前序遍历,统一代码风格迭代写法
    TreeNode* invertTree(TreeNode* root) {
        stack<TreeNode*> st;
        if (root != NULL) st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();
            if (node != NULL) {              
                st.pop();
                if (node->right) st.push(node->right);  // 右
                if (node->left) st.push(node->left);    // 左
                st.push(node);                          // 中
                st.push(NULL);
            }
            else {
                st.pop();
                node = st.top();
                st.pop();
                swap(node->left, node->right);
            }
        }
        return root;
    }
};

class Solution3 {
public:
    // 递归法
    TreeNode* invertTree(TreeNode* root) {
        if (root == NULL) return root;
        swap(root->left, root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

class Solution4 {
public:
    // 层序遍历法
    TreeNode* invertTree(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        vector<vector<int>> result;
        while (!que.empty()) {
            int size = que.size();  // size必须固定, que.size()是不断变化的
            for (int i = 0; i < size; ++i) {
                TreeNode* node = que.front();
                swap(node->left, node->right);
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return root;
    }
};

void my_print2(vector<vector<int>>& v, string str) {
    cout << str << endl;
    for (vector<vector<int>>::iterator vit = v.begin(); vit < v.end(); ++vit) {
        for (vector<int>::iterator it = (*vit).begin(); it < (*vit).end(); ++it) {
            cout << *it << ' ';
        }
        cout << endl;
    }
}

// 前序遍历递归法创建二叉树,每次迭代将容器首元素弹出(弹出代码还可以再优化)
void Tree_Generator(vector<string>& t, TreeNode*& node) {
    if (t[0] == "NULL" || !t.size()) return;    // 退出条件
    else {
        node = new TreeNode(stoi(t[0].c_str()));    // 中
        t.assign(t.begin() + 1, t.end());
        Tree_Generator(t, node->left);              // 左
        t.assign(t.begin() + 1, t.end());
        Tree_Generator(t, node->right);             // 右
    }
}

vector<vector<int>> levelOrder(TreeNode* root) {
    queue<TreeNode*> que;
    if (root != NULL) que.push(root);
    vector<vector<int>> result;
    while (!que.empty()) {
        int size = que.size();  // 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);
        }
        result.push_back(vec);
    }
    return result;
}

int main()
{
    vector<string> t = { "4", "2", "1", "NULL", "NULL", "3", "NULL", "NULL", "7", "6", "NULL", "NULL", "9", "NULL", "NULL" };   // 前序遍历
    TreeNode* root = new TreeNode();
    Tree_Generator(t, root);
    vector<vector<int>> tree = levelOrder(root);
    my_print2(tree, "目标树:");
    
    Solution2 s1;
    root = s1.invertTree(root);
    tree = levelOrder(root);
    my_print2(tree, "翻转后:");
    system("pause");
    return 0;
}

end

你可能感兴趣的:(算法,算法)