二叉樹轉為單鏈表——Flatten Binary Tree to Linked List


給定一刻二叉樹,將二叉樹按照前序遍歷的順序轉為單鏈表,右指針指向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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM