038翻转二叉树

翻转二叉树

题目链接:https://leetcode.cn/problems/invert-binary-tree/description/?envType=study-plan-v2\&envId=top-100-liked

我的解答:

复制代码
public TreeNode invertTree(TreeNode root) {
    if(root==null){
        return null;
    }
    TreeNode temp=root.left;
    root.left=root.right;
    root.right=temp;
    invertTree(root.left);
    invertTree(root.right);
    return root;
}

分析:代码的时间复杂度为O(n),空间复杂度为O(n)。

看了官方题解后的解答:

复制代码
//官方题解的思路与我的解题思路相同
public TreeNode invertTree(TreeNode root) {
    if(root==null){
        return null;
    }
    TreeNode left = invertTree(root.left);
    TreeNode right = invertTree(root.right);
    root.left=right;
    root.right=left;
    return root;
}

分析:代码的时间复杂度为O(n),空间复杂度为O(n),使用的空间由递归栈的深度决定,它等于当前节点在二叉树中的高度。在平均情况下,二叉树的高度与节点个数为对数关系,即 O(logn)。而在最坏情况下,树形成链状,空间复杂度为 O(n)。

总结

  • 本题的本质还是二叉树的深度优先搜索(递归)。
相关推荐
老师我太想进步了20262 小时前
【数据结构-8】栈的实现
c语言·数据结构·算法
Pniubi5 小时前
力扣19 . 删除表的倒数第N个节点(栈)
算法·leetcode·职场和发展
文丑颜不良啊20 小时前
LeetCode2761~2780题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2841~2860题目解析
java·leetcode
【心态好不摆烂】1 天前
数据结构基础精讲3
数据结构·算法
岑梓铭1 天前
《考研408数据结构》第七章(B树 和 B+树)复习笔记
数据结构·笔记·b树·考研·408
文丑颜不良啊1 天前
LeetCode2921~2940题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2901~2920题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2861~2880题目解析
java·leetcode
岑梓铭1 天前
《考研408数据结构》第八章(排序)复习笔记
数据结构·笔记