题目描述
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
提示:
树中节点数目范围在 [0, 100]
内
-100 <= Node.val <= 100
题解:递归
思路与算法
这是一道很经典的二叉树问题。显然,我们从根节点开始,递归地对树进行遍历,并从叶子节点先开始翻转。如果当前遍历到的节点 root 的左右两棵子树都已经翻转,那么我们只需要交换两棵子树的位置,即可完成以 root 为根节点的整棵子树的翻转。文章来源:https://www.toymoban.com/news/detail-834621.html
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
// Define a function that inverts a binary tree
struct TreeNode* invertTree(struct TreeNode* root) {
// Base case: if the current node is NULL, return NULL
if (root == NULL) {
return NULL;
}
// Recursively invert the left subtree
struct TreeNode* left = invertTree(root->left);
// Recursively invert the right subtree
struct TreeNode* right = invertTree(root->right);
// Swap the left and right subtrees of the current node
root->left = right;
root->right = left;
// Return the root of the inverted binary tree
return root;
}
复杂度分析
- 时间复杂度:O(N),其中 N 为二叉树节点的数目。我们会遍历二叉树中的每一个节点,对每个节点而言,我们在常数时间内交换其两棵子树。
- 空间复杂度:O(N)。使用的空间由递归栈的深度决定,它等于当前节点在二叉树中的高度。在平均情况下,二叉树的高度与节点个数为对数关系,即 O(logN)。而在最坏情况下,树形成链状,空间复杂度为 O(N)。
作者:力扣官方题解
链接:https://leetcode.cn/problems/invert-binary-tree/solutions/415160/fan-zhuan-er-cha-shu-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。文章来源地址https://www.toymoban.com/news/detail-834621.html
到了这里,关于【力扣 - 翻转二叉树】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!