作業幫筆試7.31

1.非遞歸中序遍歷

用棧的方式完成,由於後進先出的特性,不斷壓入根節點的所有左節點直到當前節點爲空,然後彈出節點,並且遍歷節點的右節點。如果有節點有左子樹,則繼續壓入。。

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        # cur當做指針
        cur = root
        res = []
        stack = []
        while cur or stack:
            # 把左子樹壓入棧中
            while cur:
                stack.append(cur)
                cur = cur.left
            # 輸出棧頂元素
            cur = stack.pop()
            res.append(cur.val)
            # 檢查右子樹
            cur = cur.right
        return res

2. 重建二叉樹

根據前序和中序遍歷,返回後序遍歷

class Solution:
    # 返回構造的TreeNode根節點
    def reConstructBinaryTree(self, pre, tin):
        if len(pre) == 0:
            return None
        if len(pre) == 1:
            # 按照樹節點的結構定義!!!
            return TreeNode(pre[0])
        # 找到根節點,按照樹節點的結構定義!!!
        root = TreeNode(pre[0])
        # 在中序遍歷中找到根節點,並且劃分左\右子樹
        root_p = tin.index(root.val)
        root.left = self.reConstructBinaryTree(pre[1:root_p+1], tin[:root_p])
        # 注意下標:tin[root_p+1:]
        root.right = self.reConstructBinaryTree(pre[root_p+1:], tin[root_p+1:])
        return root

3. 用兩個隊列實現一個棧

解法:一個隊列放入,一個隊列輸出。因爲棧是後入先出,所以把q1的元素依次刪除並插入q2,再刪除最後一個元素。然後q1賦值爲q2,q2初始化爲空,這樣才能不斷刪除。

 # 用兩個隊列實現一個棧
    class Stack:
        def __init__(self):
            self.q1 = []
            self.q2 = []

        def append(self, nums):
            self.q1.append(nums)
            return self.q1

        def pop(self):
            while len(self.q1) != 1:
                self.q2.append(self.q1.pop(0))
            stack_top = self.q1.pop(0)
            self.q1 = self.q2
            self.q2 = []
            return stack_top


    a = Stack()
    a.append(1)
    a.append(2)
    a.append(3)
    a.append(4)
    print(a.append(5))
    print(a.pop())
    print(a.pop())
    print(a.append(7))

4. 定義類的規範!

注意格式:面試時,class 之後加上名稱,不帶括號;初始化定義寫法爲def。self代表類的實例。

class Person:
    def __init__(self, name = 'Charlie', age=8):
        self.name = name
        self.age = age
    def say(self, content):
        print(content)

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章