226. 翻转二叉树

1.题目介绍

给你一棵二叉树的根节点 \(root\) ,翻转这棵二叉树,并返回其根节点。

示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

示例 2:

输入:root = [2,1,3]
输出:[2,3,1]

示例 3:

输入:root = []
输出:[]

提示:

  • 树中节点数目范围在 \([0, 100]\)
  • \(-100 <= Node.val <= 100\)

2.题解

2.1 深度优先搜索(递归)

思路

使用深度优先搜索,只要子节点都翻转完毕,在翻转当前层的根节点与其兄弟节点即可。

代码

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

2.2 BFS 广度优先搜索

思路

使用队列存储当前层数所有节点,利用队列先进先出的特性实现: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) {
        if(root == nullptr) return nullptr;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            TreeNode* curr = q.front();
            q.pop();
            TreeNode* temp = curr->right;
            curr->right = curr->left;
            curr->left = temp;
            if(curr->left != nullptr) q.push(curr->left); 
            if(curr->right != nullptr) q.push(curr->right);         
        }
        return root;
    }
};

2.3 DFS广度优先搜索(用栈消除递归)

思路

使用栈消除递归,利用栈先进后出的特性实现:深度优先搜素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) {
        if(!root) return nullptr;
        stack<TreeNode*> stk;
        stk.push(root);
        while(!stk.empty()){
            TreeNode* curr = stk.top();
            stk.pop();
            TreeNode* temp = curr->right;
            curr->right = curr->left;
            curr->left = temp;
            if(curr->right != nullptr) stk.push(curr->right);
            if(curr->left != nullptr) stk.push(curr->left);
        }
        return root;
    }
};
posted @ 2023-12-13 22:32  DawnTraveler  阅读(2)  评论(0编辑  收藏  举报