zoukankan      html  css  js  c++  java
  • 2021.2.3 刷题(二叉树翻转)

    题目链接:https://leetcode-cn.com/problems/invert-binary-tree/
    题目描述:

    方法一:层序遍历(BFS)
    采用层序遍历的方式,每遍历一个节点,就将该节点的左右孩子交换。

    /**
     * Definition for a binary tree node.
     * 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) {}
     * };
     */
    class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
            queue<TreeNode *> que;
            if(root != nullptr)
                que.push(root);
            while(!que.empty())
            {
                TreeNode *node = que.front();
                que.pop();
                swap(node->left, node->right);  //交换左右孩子
                if(node->left) que.push(node->left);
                if(node->right) que.push(node->right);
            }
            return root;
        }
    };
    

    2.迭代法(前序遍历)DFS

    /**
     * Definition for a binary tree node.
     * 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) {}
     * };
     */
    class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
            stack<TreeNode*> st;
            if(root != nullptr)
                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;
        }
    };
    

    3.递归法

    class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
           
           if(root == nullptr)
                return root;
            swap(root->left, root->right);
            invertTree(root->left);
            invertTree(root->right);
            return root;
        }
    };
    
    
  • 相关阅读:
    poj3294 Life Forms(后缀数组)
    1628. White Streaks(STL)
    1523. K-inversions(K逆序对)
    1890. Money out of Thin Air(线段树 dfs转换区间)
    1350. Canteen(map)
    1521. War Games 2(线段树解约瑟夫)
    1003. Parity(并查集)
    1470. UFOs(三维树状数组)
    1471. Tree(LCA)
    1494. Monobilliards(栈)
  • 原文地址:https://www.cnblogs.com/ZigHello/p/14367187.html
Copyright © 2011-2022 走看看