摘要:題目鏈接思路如果需要反轉(zhuǎn)一個(gè)二叉樹(shù),那么我們需要遍歷整個(gè)樹(shù)的所有節(jié)點(diǎn)。這兩種辦法分別可以用迭代或者遞歸的辦法實(shí)現(xiàn)。算法復(fù)雜度遞歸時(shí)間空間時(shí)間空間代碼遞歸
題目鏈接:Invert Binary Tree
思路:
如果需要反轉(zhuǎn)一個(gè)二叉樹(shù),那么我們需要遍歷整個(gè)樹(shù)的所有節(jié)點(diǎn)。
如果想遍歷所有的節(jié)點(diǎn),我們可以用Depth First Search(DFS)或者Breadth First Search(BFS)。
這兩種辦法分別可以用迭代(iterative)或者遞歸(recursive)的辦法實(shí)現(xiàn)。
算法復(fù)雜度:
遞歸:
時(shí)間:O(n) where n is the number of nodes 空間:O(n)
DFS/BFS:
時(shí)間:O(n) where n is the number of nodes 空間:O(n)
代碼:
遞歸:
class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root: root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root
DFS (Stack):
class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ stack = [root] while stack: node = stack.pop() if node: node.left, node.right = node.right, node.left stack.extend([node.right, node.left]) return root
BFS (Queue):
class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ queue = [root] while queue: node = queue.pop(0) if node: node.left, node.right = node.right, node.left queue.extend([node.left, node.right]) return root
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/41930.html
摘要:題目鏈接題目分析反轉(zhuǎn)二叉樹(shù)。思路類(lèi)似反轉(zhuǎn)兩個(gè)變量,先把左右子樹(shù)存進(jìn)單獨(dú)的變量,再相互覆蓋左右子樹(shù)。并對(duì)子樹(shù)進(jìn)行相同的操作。最終代碼若覺(jué)得本文章對(duì)你有用,歡迎用愛(ài)發(fā)電資助。 D59 226. Invert Binary Tree 題目鏈接 226. Invert Binary Tree 題目分析 反轉(zhuǎn)二叉樹(shù)。 思路 類(lèi)似反轉(zhuǎn)兩個(gè)變量,先把左右子樹(shù)存進(jìn)單獨(dú)的變量,再相互覆蓋左右子樹(shù)。 并...
Problem Invert a binary tree. Example: Input: 4 / 2 7 / / 1 3 6 9 Output: 4 / 7 2 / / 9 6 3 1 Trivia:This problem was inspired by this original t...
摘要:算法思路判斷樹(shù)是否為空同時(shí)也是終止條件。分別對(duì)左右子樹(shù)進(jìn)行遞歸。代碼實(shí)現(xiàn)判斷當(dāng)前樹(shù)是否為左右子樹(shù)結(jié)點(diǎn)交換分別對(duì)左右子樹(shù)進(jìn)行遞歸返回樹(shù)的根節(jié)點(diǎn)歡迎一起加入到開(kāi)源倉(cāng)庫(kù),可以向提交您其他語(yǔ)言的代碼。 Time:2019/4/21Title: Invert Binary TreeDifficulty: EasyAuthor: 小鹿 題目:Invert Binary Tree(反轉(zhuǎn)二叉樹(shù)) ...
摘要:原題鏈接遞歸法復(fù)雜度時(shí)間空間遞歸??臻g思路這個(gè)難倒大神的題也是非常經(jīng)典的一道測(cè)試對(duì)二叉樹(shù)遍歷理解的題。遞歸的終止條件是當(dāng)遇到空節(jié)點(diǎn)或葉子節(jié)點(diǎn)時(shí),不再交換,直接返回該節(jié)點(diǎn)。代碼給出的是后序遍歷的自下而上的交換,先序遍歷的話就是自上而下的交換。 Invert Binary Tree Invert a binary tree. 4 / 2 7 / ...
摘要:微信公眾號(hào)記錄截圖記錄截圖目前關(guān)于這塊算法與數(shù)據(jù)結(jié)構(gòu)的安排前。已攻略返回目錄目前已攻略篇文章。會(huì)根據(jù)題解以及留言?xún)?nèi)容,進(jìn)行補(bǔ)充,并添加上提供題解的小伙伴的昵稱(chēng)和地址。本許可協(xié)議授權(quán)之外的使用權(quán)限可以從處獲得。 Create by jsliang on 2019-07-15 11:54:45 Recently revised in 2019-07-15 15:25:25 一 目錄 不...
閱讀 2564·2023-04-26 00:56
閱讀 2013·2021-10-25 09:46
閱讀 1250·2019-10-29 15:13
閱讀 823·2019-08-30 15:54
閱讀 2207·2019-08-29 17:10
閱讀 2628·2019-08-29 15:43
閱讀 507·2019-08-29 15:28
閱讀 3040·2019-08-29 13:24