N叉樹的三種遍歷(層次遍歷、前序遍歷、后序遍歷)
題目鏈接:
1、層次遍歷
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] queue = collections.deque() queue.append(root) res = [] while queue: size = len(queue) temp = [] for _ in range(size): node = queue.popleft() temp.append(node.val) if node.children: queue.extend(node.children) res.append(temp) return res
2、前序遍歷
前序遍歷就是從左至右,先根后孩子;遞歸比較簡單,迭代法的話需要借助一個輔助棧,把每個節(jié)點的孩子都壓入棧中;
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def preorder(self, root: 'Node') -> List[int]: if not root: return [] #迭代法 stack, output = [root, ], [] while stack: root = stack.pop() output.append(root.val) stack.extend(root.children[::-1]) return output #遞歸法 res = [] def helper(root): if not root: return res.append(root.val) for children in root.children: helper(children) helper(root) return res
3、后序遍歷
在后序遍歷中,我們會先遍歷一個節(jié)點的所有子節(jié)點,再遍歷這個節(jié)點本身。例如當(dāng)前的節(jié)點為 u,它的子節(jié)點為 v1, v2, v3 時,那么后序遍歷的結(jié)果為 [children of v1], v1, [children of v2], v2, [children of v3], v3, u,其中 [children of vk] 表示以 vk 為根節(jié)點的子樹的后序遍歷結(jié)果(不包括 vk 本身)。我們將這個結(jié)果反轉(zhuǎn),可以得到 u, v3, [children of v3]', v2, [children of v2]', v1, [children of v1]',其中 [a]' 表示 [a] 的反轉(zhuǎn)。此時我們發(fā)現(xiàn),結(jié)果和前序遍歷非常類似,只不過前序遍歷中對子節(jié)點的遍歷順序是 v1, v2, v3,而這里是 v3, v2, v1。
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def postorder(self, root: 'Node') -> List[int]: if not root: return [] #后續(xù)遍歷是先遍歷一個節(jié)點的孩子節(jié)點,在去遍歷這個節(jié)點本身 #遞歸 result = [] def postHelper(root): if not root: return None children = root.children for child in children: postHelper(child) result.append(root.val) postHelper(root) return result #迭代法:輔助棧 res = [] stack = [root,] while stack: node = stack.pop() if node is not None: res.append(node.val) for children in node.children: stack.append(children) return res[::-1]
總結(jié):N叉樹和二叉樹的差別不是很多,唯一的差別就是孩子很多不需要去判斷左右孩子了。
到此這篇關(guān)于N叉樹的三種遍歷(層次遍歷、前序遍歷、后序遍歷)的文章就介紹到這了,更多相關(guān)N叉樹的三種遍歷內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Qt中PaintEvent繪制實時波形圖的實現(xiàn)示例
本文主要介紹了Qt中PaintEvent繪制實時波形圖的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06C語言中QString與QByteArray互相轉(zhuǎn)換的方法
本文主要介紹了C語言中QString與QByteArray互相轉(zhuǎn)換的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05利用Debug調(diào)試代碼解決0xC0000005:?讀取位置?0x0000000000000000?時發(fā)生訪問沖突問
這篇文章主要介紹了利用Debug調(diào)試代碼解決0xC0000005:?讀取位置?0x0000000000000000?時發(fā)生訪問沖突,本文給大家分享完美解決方案,需要的朋友可以參考下2023-03-03