算法与数据结构 / 29

数据结构练习:层序、双栈与最大值栈

数据结构、边界条件与实现过程。 数据结构练习:层序、双栈与最大值栈。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

1. Print the binary tree in the level order

层序: 根10;下一层5、15;再下一层2、7、12、20。当前层队列取空后再替换成下一层队列,避免把不同层的输出混在一起。

PYTHON · 仅供阅读
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
PYTHON · 仅供阅读
from collections import deque
      
def level(root):
    if root is None:
        return
    q = deque([root])
    next = deque()
    line = deque()
    while q:
        head = q.popleft()
        if head.left:
            next.append(head.left)
        if head.right:
            next.append(head.right)
        line.append(head.val)
        if not q:
            print(line)
            if next:
                q = next
                next = deque()
                line = deque()
PYTHON · 仅供阅读
# Test case
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.left.left = TreeNode(2)
root.left.right = TreeNode(7)
root.right.left = TreeNode(12)
root.right.right = TreeNode(20)

level(root)
原笔记输出 · 本次未执行
deque([10])
deque([5, 15])
deque([2, 7, 12, 20])

2. Flip tree

Given a BT where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.

上下翻转: 1(2,3), 2(4,5)变为4(5,2), 2(3,1)。左右含义写成node(left,right),空子节点省略;原根1成为最右叶。

->

局部重连: 保存递归返回的新根;将原left的左指针接原right、右指针接原root;清空原root两条旧边,避免形成环。

PYTHON · 仅供阅读
## Recursion rule
A -> root
root.left.left = root.right
root.left.right = root
root.left = None
root.right = None

TC=O(n)TC=O(n)
SC=O(height)SC=O(\text{height})

PYTHON · 仅供阅读
def upside_tree(root):
    if not root:
        return root
    if not root.left and not root.right:
        return root
    new_root = upside_tree(root.left)
    root.left.left = root.right
    root.left.right = root
    root.left = None
    root.right = None
    return new_root

3. Implement a queue using two stacks

Amortized TC:

摊还分析: 每个元素至多压入s1一次、从s1弹出一次、压入s2一次、从s2弹出一次。n个元素的总移动O(n),所以操作序列的摊还成本O(1);单次批量转移仍可能O(n)。

TC=O(1)TC=O(1)

TC={O(1),amortizedO(n),worst caseTC= \begin{cases} O(1), & \text{amortized} \\ O(n), & \text{worst case} \\ \end{cases}
PYTHON · 仅供阅读
class Queue(object):
    def __init__(self):
        self.s1 = []
        self.s2 = []
        self.head = None

    def enqueue(self, x):  # TC:O(1)
        if not self.s1:
            self.head = x
        self.s1.append(x)

    def dequeue(self):  # amortized TC:O(1), worst O(n)
        if not self.s2:
            while self.s1:
                self.s2.append(self.s1.pop())
        return self.s2.pop()

    def is_empty(self):
        return not self.s1 and not self.s2

    def peek(self):
        if self.s2:
            return self.s2[-1]
        return self.head

    def size(self):
        return len(self.s1) + len(self.s2)

整理注: 原dequeue对空队列会抛IndexError;peek在队列已空时可能返回旧head。调用前需检查is_empty。两栈总空间O(n),单次最坏出队O(n),摊还O(1)。

4. Implement a stack with MAX API

带最大值的栈: push 1、2、0、3后依次存[(1,1),(2,2),(0,2),(3,3)],每个二元组为当前值和截至该位置的最大值;pop后新的栈顶即恢复先前最大值。

TC=O(1)TC=O(1)
SC=O(n)SC=O(n)

PYTHON · 仅供阅读
class Stack(object):
    def __init__(self):
        self.stack = []

    def is_empty(self):
        return len(self.stack) == 0

    def max(self):
        if not self.is_empty():
            return self.stack[-1][1]
        raise Exception('max(): empty stack')

    def push(self, x):
        tmp = x
        if not self.is_empty():
            tmp = max(tmp, self.max())
        self.stack.append((x, tmp))

    def pop(self):
        if self.is_empty():
            raise Exception('pop(): empty stack')
        elem = self.stack.pop()
        return elem[0]

5. Binary tree traversal (non-recursion)

How many times a node has been accessed during the traversal? 3

  • preorder
PYTHON · 仅供阅读
def preorder_traversal(root):
    output = []
    if not root:
        return output
    stack = [(root, 1)]
    while stack:
        node, count = stack.pop()
        if count == 1:
            output.append(node.val)
            stack.append((node, count + 1))
            if node.left:
                stack.append((node.left, 1))
        if count == 2:
            stack.append((node, count + 1))
            if node.right:
                stack.append((node.right, 1))
        if count == 3:
            continue
    return output
  • inorder
PYTHON · 仅供阅读
def inorder_traversal(root):
    output = []
    if not root:
        return output
    stack = [(root, 1)]
    while stack:
        node, count = stack.pop()
        if count == 1:
            stack.append((node, count + 1))
            if node.left:
                stack.append((node.left, 1))
        if count == 2:
            output.append(node.val)
            stack.append((node, count + 1))
            if node.right:
                stack.append((node.right, 1))
        if count == 3:
            continue
    return output
  • postorder
PYTHON · 仅供阅读
def postorder_traversal(root):
    output = []
    if not root:
        return output
    stack = [(root, 1)]
    while stack:
        node, count = stack.pop()
        if count == 1:
            stack.append((node, count + 1))
            if node.left:
                stack.append((node.left, 1))
        if count == 2:
            stack.append((node, count + 1))
            if node.right:
                stack.append((node.right, 1))
        if count == 3:
            output.append(node.val)
    return output

整理参考资料