Leetcode June challenge ( Invert Binary Tree )

In time, you will call me master -- Star Wars

Week 1 Invert Binary Tree

http://img2.58codes.com/2024/20116751G0WJuwsNAQ.png

Solution 1

using list as stack
class Solution:    def invertTree(self, root: TreeNode) -> TreeNode:        invert_node = TreeNode()        queue = []        queue.append(root)        while(queue):            tmp_queue = queue.pop(0)            if tmp_queue:                tmp_queue.left, tmp_queue.right = tmp_queue.right, tmp_queue.left                queue.append(tmp_queue.left)                queue.append(tmp_queue.right)        return root
stack ( last-in , first-out )invert binary tree : tmp_queue.left, tmp_queue.right = tmp_queue.right, tmp_queue.left

Solution 2

using deque ( list as queue )
from collections import deque class Solution:    def invertTree(self, root: TreeNode) -> TreeNode:        invert_node = TreeNode()        queue = deque([root])        while queue:            item = queue.popleft()            if item:                item.left, item.right = item.right, item.left                queue.append(item.left)                queue.append(item.right)        return root
queue ( first-in, last-out )queue pop first item -- > popleft()

important take away

Deques have O(1) speed for appendleft() and popleft()lists have O(n) performance for insert(0, value) and pop(0)

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章