目录

三个月算法进阶--day59

栈空间

空间复杂度,二叉树退化为链表,O(n)

平行赋值与暂存

用栈遍历,入栈暂存节点

leetcode剑指offer第27题二叉树的镜像

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root: return
        stack = [root]
        while stack:
            node = stack.pop()
            if node.left: stack.append(node.left)
            if node.right: stack.append(node.right)
            node.left, node.right = node.right, node.left
        return root

记录

leetcode剑指offer第28题对称的二叉树

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        def recur(left, right):
            if not left and not right:
                return True
            if not left or not right or left.val != right.val:
                return False
            return recur(left.left, right.right) and recur(left.right, right.left)
        
        if not root:
            return True
        return recur(root.left, root.right)