算法与数据结构 / 31

树递归:规模、深度与BST验证

数据结构、边界条件与实现过程。 树递归:规模、深度与BST验证。

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

PYTHON · 仅供阅读
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

1. Get height of a Tree

TC=O(n)TC = O(n)
SC=O(h)SC = O(h)

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)

2. Get size of a Tree

TC=O(n)TC = O(n)
SC=O(h)SC = O(h)

PYTHON · 仅供阅读
def get_size(root):
    if not root:
        return 0
    left = get_size(root.left)
    right = get_size(root.right)
    return 1 + left + right

3. For each node in a tree, store the number of nodes in its left child subtree

子树规模返回值: 每节点返回1+左规模+右规模,并把左规模写到total_left。叶的left_total=0;例如根左子树含3节点,根记录3,而不是包含根自身的4。

PYTHON · 仅供阅读
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
        self.total_left = 0 # how many nodes in its left-subtree
PYTHON · 仅供阅读
def store_left_total(node):
    if node is None:
        return 0
    left_total = store_left_total(node.left)
    right_total = store_left_total(node.right)
    node.total_left = left_total
    return 1 + left_total + right_total

4. Find the node with the max difference in the total number of descendants in its left subtree and right subtree

左右规模差: 对每节点计算abs(left_size-right_size)并更新全局最优,返回给父节点的仍是该子树总规模。下一段测试中节点2只有两个右侧后代,规模差为2。

4.1 Global variable

TC=O(n)TC = O(n)
SC=O(h)SC = O(h)

PYTHON · 仅供阅读
global_max = -1  # -1为无效差值
res = None

def node_diff(root):
    if root is None:
        return 0
    left_total = node_diff(root.left)
    right_total = node_diff(root.right)
    global global_max
    global res
    if abs(left_total - right_total) > global_max:
        global_max = abs(left_total - right_total)
        res = root
    return left_total + right_total + 1


def get_max_diff(root):
    global res
    node_diff(root)
    return res
PYTHON · 仅供阅读
# Test case
root0 = TreeNode(0)
root0.left = TreeNode(1)
root0.left.left = TreeNode(3)
root0.left.right = TreeNode(4)
root0.right = TreeNode(2)
root0.right.right = TreeNode(5)
root0.right.right.right = TreeNode(6)

res_node0 = get_max_diff(root0)
print(res_node0.val)
原笔记输出 · 本次未执行
2

global variable的问题:

PYTHON · 仅供阅读
get_max_diff(0) => global_max = 2, res = 2 => return 2 # correct
get_max_diff(None) => global_max = 2, res = 2 => return 2 # wrong!!

4.2 No global variable

TC=O(n)TC = O(n)
SC=O(h)SC = O(h)

PYTHON · 仅供阅读
class ResultWrapper(object):
    def __init__(self):
        self.global_max = -1
        self.solution = None


def max_diff_node(root, res):
    if not root:
        return 0
    left_total = max_diff_node(root.left, res)
    right_total = max_diff_node(root.right, res)
    if abs(left_total - right_total) > res.global_max:
        res.global_max = abs(left_total - right_total)
        res.solution = root
    return left_total + right_total + 1


def max_diff(root):
    res = ResultWrapper()
    max_diff_node(root, res)
    return res.solution
PYTHON · 仅供阅读
# Test case
res_node1 = max_diff(root0)
print(res_node1.val)
原笔记输出 · 本次未执行
2

5. Given a binary tree, find its minimum height

The minimum height is the number of nodes along the shortest path from the root node down to the nearest leaf node.

5.1 Wrong solution: Choose root is None as base case

Wrong!! 无法区分root是否为leaf节点

PYTHON · 仅供阅读
def getHeight_min_wrong(root):
    if root is None:
        return 0
    left = getHeight_min_wrong(root.left)
    right = getHeight_min_wrong(root.right)
    return min(left, right) + 1
PYTHON · 仅供阅读
# Test case
root1 = TreeNode(0)
root1.right = TreeNode(1)
root1.right.right = TreeNode(2)
root1.right.right.right = TreeNode(3)

print(getHeight_min_wrong(root1))
原笔记输出 · 本次未执行
1

5.2 Choose leaf (root.left is None and root.right is None) as base case

TC=O(n)TC = O(n)
SC=O(h)SC = O(h)

PYTHON · 仅供阅读
def getHeight_min(root):
    if root is None:  # Edge case, just to handle root is None
        return 0
    if root.left is None and root.right is None:  # Base case, leaf node
        return 1
    left = getHeight_min(root.left) if root.left else float('inf')  # float('inf')代表无穷大
    right = getHeight_min(root.right) if root.right else float('inf')
    return min(left, right) + 1
PYTHON · 仅供阅读
# Test case
print(getHeight_min(root1))
原笔记输出 · 本次未执行
4

6. Given a binary tree, write a function to determine whether this tree is a binary search tree

TC=O(n)TC = O(n)
SC=O(h)SC = O(h)

6.1 Check all the values inside a binary tree, all of them should reside in the range (min, max)

PYTHON · 仅供阅读
def BST(root):
    if root is None:
        return True
    min_val = float('-inf')
    max_val = float('inf')
    return isBST(root, min_val, max_val)


def isBST(root, min_val, max_val):
    if root is None:
        return True
    if root.val <= min_val or root.val >= max_val:
        return False
    return isBST(root.left, min_val, root.val) and \
           isBST(root.right, root.val, max_val)

6.2 Inorder traversal: 判断下一个node是否比上一个node大

PYTHON · 仅供阅读
def isValidBST(root):
    prev = [None]
    res = [True]
    inorder(root, prev, res)
    return res[0]


def inorder(root, prev, res):
    if not root:
        return
    inorder(root.left, prev, res)
    if prev[0] is not None and prev[0] >= root.val:
        res[0] = False
    prev[0] = root.val
    inorder(root.right, prev, res)

Change to Class

PYTHON · 仅供阅读
class Solution(object):
    def __init__(self):
        self.prev = None

    def isValidBST(self, root):
        self.prev = None
        return self.impl(root)

    def impl(self, root):
        if not root:
            return True
        if not self.impl(root.left):
            return False
        if self.prev is not None and self.prev >= root.val:
            return False
        self.prev = root.val
        return self.impl(root.right)

6.3 从下往上返值

Way of thinking (Tricks)

  1. What do you expect from your left/right child?
    • left_res :左子树是否为BST/左子树最小值/左子树最大值
    • right_res:右子树是否为BST/右子树最小值/右子树最大值
  2. What do you want to do in current layer?
    • PYTHON · 仅供阅读
    isBST = left_res.isBST and right_res.isBST and left_res.max < root.val and right_res.min > root.val
    PLAINTEXT · 仅供阅读
  3. What do you want to return to your parent? *
    PYTHON · 仅供阅读
    return (isBST, left_res.min or root.val, right_res.max or root.val)

整理注: 若某子树极值为0,不能用or把它当成缺省值;下方正式实现已改为显式None判断。

PYTHON · 仅供阅读
def isValidBST(root):
    return isBSTHelper(root)[0]


def isBSTHelper(root):
    if not root:
        # tuple[0]代表是否BST,[1]代表最小值,[2]代表最大值
        return (True, None, None)
    
    left_res = isBSTHelper(root.left)
    right_res = isBSTHelper(root.right)
    
    # 判断left_res和right_res是否为BST,如果不是,返回Fasle
    if not left_res[0] or not right_res[0]:
        return (False, None, None)
    
    # 判断root.val是否大于left_res的max,如果不是,返回Fasle
    if left_res[2] is not None and root.val <= left_res[2]:
        return (False, None, None)
    
    # 判断root.val是否小于right_res的min,如果不是,返回Fasle
    if right_res[1] is not None and root.val >= right_res[1]:
        return (False, None, None)
    
    # 返回(True, root下的最小值, root下的最大值)
    return (True, left_res[1] if left_res[1] is not None else root.val, right_res[2] if right_res[2] is not None else root.val)

整理参考资料