1. 程式人生 > 實用技巧 >力扣_二叉樹卡片題目答案彙總

力扣_二叉樹卡片題目答案彙總

題目來源

力扣二叉樹複習題目

這裡只是附上各個程式碼答案,並不做解釋,至少現在不做解釋。

程式碼

二叉樹類

from collections import deque

# 數的節點類
class TreeNode(object):
    def __init__(self, item):
        self.val = item
        self.left = None
        self.right = None

# python 二叉樹類
class Tree(object):
    
    def __init__(self):
        self.root = None
        self.res = 0
    
    def construct_tree(self, values=None):
        if not values:
            return None
        self.root = TreeNode(values[0])
        queue = deque([self.root])
        leng = len(values)
        nums = 1
        while nums < leng:
            node = queue.popleft()
            if node:
                node.left = TreeNode(values[nums]) if values[nums] else None
                queue.append(node.left)
                if nums + 1 < leng:
                    node.right = TreeNode(values[nums + 1]) if values[nums + 1] else None
                    queue.append(node.right)
                    nums += 1
                nums += 1
    
    def bfs(self):
        res = []
        queue = deque([self.root])
        while queue:
            node = quque.popleft()
            if node:
                res.append(node.val)
                queue.append(node.left)
                queue.append(node.right)
        return ret
    # 迭代遍歷,資料儲存一層一個列表
#     if not root:
#         return []
#     queue = deque([self.root])
#     ret = []
#     while queue:
#         list_1 = []
#         for i in range(len(queue)):
#             node = queue.popleft()
#             if node.left:
#                 queue.append(node.left)
#             if node.right:
#                 queue.append(node.right)
#             list_1.append(node.val)
#         ret.append(list_1)
#     return ret
            
    def pre_traversal(self):
        ret = []
        # 遞迴方式
#         def traversal(head):
#             if not head:
#                 return
#             ret.append(head.val)
#             traversal(head.left)
#             traversal(head.right)
#         traversal(self.root)
        # 迭代方式
        if not root:
            return []
        stack = [self.root]
        while stack:
            node = stack.pop()
            ret.append(node.val)
            if node.right:  # 先加右子節點,因為列表pop先拋卻最右的,
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        return ret
    
    def in_traversal(self):
        # 遞迴方式
#         ret = []
#         def traversal(head):
#             if not head:
#                 return 
#             traversal(head.left)
#             ret.append(head.val)
#             traversal(head.right)
#         traversal(self.root)
        # 迭代方式
        if not root:
            return []
        ret = []
        stack = []
        root = self.root
        while stack or root:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            ret.append(root.val)
            root = root.right
        return ret
    
    def pre_traversal(self):
         # 遞迴方式
#         ret = []
#         def traversal(head):
#             if not head:
#                 return 
#             traversal(head.left)
#             traversal(head.right)
#             ret.append(head.val)
#         traversal(self.root)
#         return ret
        # 迭代方式
        if not root:
            return []
        stack = [self.root]
        ret = []
        while stack:
            node = stack.pop()
            ret.append(node.val)
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        return result[::-1]
    
    def get_depth(self, node):
        # 自底向上
        if not node:
            return 0
        return max(self.get_depth(node.left) + 1, 
                   self.get_depth(node.right) + 1)
        
        # 自頂向下
    def get_depth2(self, node, depth):
        if not node:
            return
        print(f"res===>{self.res}, depth===>{depth}")
        if not node.left and not node.right:
            self.res = max(self.res, depth)
        depth += 1
        self.get_depth2(node.left, depth)
        self.get_depth2(node.right, depth)
        return self.res

問題1 二叉樹的最大深度

class Solution:
    def maxDepth(self, root):
        # 方法一:自底向上
        if not root:
            return 0
        return max(self.maxDepth(root.left) + 1, self.maxDepth(root.right) + 1)

問題2 對稱二叉樹

from collections import deque


class Solution:
    def isSymmetric(self, root):
    # 方法一:遞迴
        if not root:
            return True
        return self.isST(root.left, root.right)
    
    def isST(self, left, right):
        if not left and not right:
            return True
        if not left or not right or left.val != right.val:
            return False
        return self.isST(left.left, right.right) and self.isST(left.right, right.left)

問題3 路徑總和

class Solution:
    def hasPathSum(self, root, Pathsum):
        # 方法一:DFS
        if not root:
            return False
        if not root.left and not root.right:
            return sum == root.val
        return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)    

問題4 從中序遍歷和後序遍歷構造二叉樹

class Solution:
    def buildTree(self, inorder, postorder):
        if not inorder or not postorder:
            return None
        root = TreeNode(postorder[-1])  # 根節點
        index = inorder.index(postorder[-1])
        root.left = self.buildTree(inorder[:index], postorder[:index])
        root.right = self.buildTree(inorder[index + 1:], postorder[index:-1])
        return root

問題5 從前序與中序遍歷序列構造二叉樹

class Solution:
    def buildTree(self, preorder, inorder):
        if not preorder or not inorder:
            return None
        root = TreeNode(preorder[0])
        index = inorder.index(preorder[0])
        root.left = self.buildTree(preorder[1: 1 + index], inorder[:index])
        root.right = self.buildTree(preorder[index + 1:], inorder[index+1:])
        return root

問題6 填充每個節點到下一個右側節點指標

class Solution:
    def connect(self, root):  # root: 'Node' -> 'Node'
        # 遞迴版:
        if not root or not root.left: 
            return root

        root.left.next = root.right
        if root.next and root.right:
            root.right.next = root.next.left
        self.connect(root.left)
        self.connect(root.right)
        return root
    
        # 迭代版 
        if not root:
            return 
        
        the_root = root
        while root.left is not None:
            next_layer = root.left
            while root.next is not None:
                root.left.next = root.right
                root.right.next = root.next.left
                root = root.next
            root.left.next = root.right
            root = next_layer
        return the_root

問題7 填充每個節點的下一個右側節點指標II

class Solution:
    def connect(self, root):  # root: 'Node' -> 'Node'
        # 迭代版
        head = root
        while head:
            cur = head
            pre = head = None
            while cur:
                if cur.left:
                    if not pre:
                        pre = head = cur.left
                    else:
                        pre.next = cur.left
                        pre = pre.next
                if cur.right:
                    if not pre:
                        pre = head = cur.right
                    else:
                        pre.next = cur.right
                        pre = pre.next
                cur = cur.next
        return root

問題8 二叉樹的最近公共祖先

class Solution:
    def lowestCommonAncestor(self, root, p, q):  # root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
        if root is None:
            return None
        if root == p or root == q:
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        
        if left and right:  # p q 分別在左右兩子樹中
            return root
        if not left:        # p q 都在右子樹中
            return right
        if not right:       # p q 都在左子樹中
            return left

問題9 二叉樹的序列化與反序列化

from collections import deque


class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        """
        s = ""
        stack = [root]
        while stack:
            root = stack.pop(0)
            if root:
                s += str(root.val)
                stack.append(root.left)
                stack.append(root.right)
            else:
                s += "n"
            s += " "
        return s

        
    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        tree = data.split()
        if tree[0] == "n":
            return None
        stack = []
        root = TreeNode(int(tree[0]))
        stack.append(root)
        i = 1
        while stack:
            cur = stack.pop(0)
            if cur == None:
                continue
            cur.left = TreeNode(int(tree[i])) if tree[i] != "n" else None
            cur.right = TreeNode(int(tree[i + 1])) if tree[i + 1] != "n" else None
            i += 2
            stack.append(cur.left)
            stack.append(cur.right)
        return root