二叉樹轉為單鏈表——Flatten Binary Tree to Linked List
阿新 • • 發佈:2019-03-11
lse inf spa HERE 合並 next bsp 左右 指針
給定一刻二叉樹,將二叉樹按照前序遍歷的順序轉為單鏈表,右指針指向next,左指針指向None
1、分治法:將左、右子樹變為單鏈表,分別返回左右鏈表的最後一個節點,讓左鏈表的最後一個節點指向右節點的第一個節點,完成合並。右鏈表的最後一個節點即為整個鏈表的最後一個節點。
2、遍歷法:二叉樹的非遞歸前序遍歷。從棧頂取出節點cur,依次將cur的右節點、左節點壓入棧,然cur指向棧頂節點。
方法二 """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None""" class Solution: """ @param root: a TreeNode, the root of the binary tree @return: nothing """ def flatten(self, root): # write your code here if not root: return stack = [root] while stack: cur = stack.pop()if cur.right: stack.append(cur.right) if cur.left: stack.append(cur.left) cur.left, cur.right = None, stack[-1] if stack else None
方法一 """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None""" class Solution: """ @param root: a TreeNode, the root of the binary tree @return: nothing """ def flatten(self, root): # write your code here last = self.helper(root) def helper(self, root): if root == None: return None if root.left == None and root.right == None: return root if root.left == None: return self.helper(root.right) if root.right == None: right_last = self.helper(root.left) root.right, root.left = root.left, None return right_last left_last = self.helper(root.left) right_last = self.helper(root.right) left_last.right = root.right root.right, root.left = root.left, None return right_last
二叉樹轉為單鏈表——Flatten Binary Tree to Linked List