算法与数据结构 / 27

类、继承与树递归

数据结构、边界条件与实现过程。 类、继承与树递归。

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

1. Count the number of nodes in a binary tree.

1.1 Function

PYTHON · 仅供阅读
def count_by_preorder_traversal(root):
    res = [0]
    helper(root, res)
    return res[0]


def helper(root, res):
    if not root:
        return
    res[0] += 1
    helper(root.left, res)
    helper(root.right, res)

Why res[]? 因为不写会是0,错误

PYTHON · 仅供阅读
def count_by_preorder_traversal(root):
    res = 0
    helper(root, res)
    print(res)  # res is 0

    
def helper(root, res):
    res += 1

1.2 Class

PYTHON · 仅供阅读
class Solution(object):
    def __init__(self):
        self.res = 0
        
    def count_by_preorder_traversal(self, root):
        self.helper(root)
        return self.res
    
    def helper(self, root):
        if not root:
            return
        self.res += 1
        self.helper(root.left)
        self.helper(root.right)

        
s = Solution()
# s.count_by_preorder_traversal(aTreeNode)

整理注: 重复调用同一实例前需要把self.res重置为0;这里保留单次调用教学示例。

2. Class VS Object

  • 面向对象: Object Oriented Programming(OOP)
  • OOD: Object Oriented Design

2.1 Inheritance and Override

PYTHON · 仅供阅读
class Animal(object):
    def __init__(self):
        self.name = 'no name'
    
    def run(self):
        print('Animal is running ...')
        
    def getName(self):
        return self.name
    
    
class Dog(Animal):
    def run(self):
        super().run()  # Animal.run(self)也可以,super().run()更利于协作继承
        print('dog is running')
        
        
# Test case
dog = Dog()
dog.run()
原笔记输出 · 本次未执行
Animal is running ...
dog is running

版本说明: 上方代码含局部修正;下方/相邻输出来自原笔记运行记录(隐私字段已占位),不是本次重新运行修正版得到的结果。

2.2 下划线使用

  • 单下划线:表示protected类型变量,不能外部调用(只是约定习惯,实际可以调用)
    不能用于
    PYTHON · 仅供阅读
    from module import _foo  # python不允许
  • 双下划线:表示private变量,不能被外部访问,不能被子类访问和继承
PYTHON · 仅供阅读
class Animal(object):
    def __init__(self):
        self.__name = 'no name'        
    def run(self):
        print('Animal is running ...')     
    def getName(self):
        return self.__name  # Correct
    
class Dog(Animal):
    def run(self):
        print(self.__name)  # Wrong
        
dog = Dog()
dog.__name     # Wrong
dog.getName()  # Correct

整理注: 单下划线是非公开约定,显式 from module import _foo 合法;双下划线触发名称改写,不是安全隔离,也不阻止继承。

  • 头尾双下划线:定义的特殊方法,一般是系统/built-in的名字
PYTHON · 仅供阅读
# import包时python从上到下全执行,mian并非为函数入口
print('before main')

if __name__ == '__main__':
    print('after main')
原笔记输出 · 本次未执行
before main
after main

3. Recursion

3.1 Get height of a binary tree

高度传递: Bottom-up对空树返回0、对节点返回1+max(left,right);Top-down从根深度0出发,沿边加1,在空孩子处更新最大深度。两者计算的都是节点数高度,需统一计数约定。

  • Bottom Up(从下往上返值)
    TC=O(n)TC=O(n)
    SC=O(height)SC=O(\text{height})
PYTHON · 仅供阅读
def get_height(root):
    if not root:
        return 0
    left = get_height(root.left)
    right = get_height(root.right)
    return 1 + max(left, right)
  • Top Down(从上往下返值)
    TC=O(n)TC=O(n)
    SC=O(height)SC=O(\text{height})
PYTHON · 仅供阅读
class Solution(object):
    def findHeight(self, root):
        if not root:
            return 0
        self.result = -float('inf')
        self.helper(root, 0)
        return self.result

    def helper(self, root, depth):
        if not root:
            self.result = max(self.result, depth)
            return None
        self.helper(root.left, depth + 1)
        self.helper(root.right, depth + 1)

        return None

Top-down特点:

  1. 以参数传递信息,以一个class的attribution来记录最终结果
  2. 通常不需要返回值(而且尽量不要返)
  3. 思维上更straight-forward,但是代码不如bottom-up简洁
  4. 大部分需要输出完整path的题,top-down更实用
    如果依赖subtree的结果,使用bottom-up

3.2 Find the max path sum from root to leaf

  • Bottom Up
PYTHON · 仅供阅读
class Solution(object):
    def maxPathSumLeafToRoot(self, root):
        if not root:
            return -float('inf')
        if root.left is None and root.right is None:
            return root.val
        left = self.maxPathSumLeafToRoot(root.left)
        right = self.maxPathSumLeafToRoot(root.right)
        return max(left, right) + root.val
  • Top Down
PYTHON · 仅供阅读
class Solution1(object):
    def maxPathSumLeafToRoot(self, root):
        if not root:
            return -float('inf')
        self.retValue = -float('inf')
        self.helper(root, 0)
        return self.retValue

    def helper(self, node, curSum):
        if not node:
            return
        if node.left is None and node.right is None:
            self.retValue = max(self.retValue, curSum + node.val)
        self.helper(node.left, curSum + node.val)
        self.helper(node.right, curSum + node.val)

整理参考资料