代码随想录算法训练营第十八天 | 二叉树part06

49 阅读1分钟

代码随想录算法训练营第十八天 | 二叉树part06

530 二叉搜索树的最小绝对差

image.png

max_ = float('inf')
result = []
def dfs(node):
    if not node:
        return
    dfs(node.left)
    result.append(node.val)
    dfs(node.right)
dfs(root)
for i in range(len(result)-1):
    max_ = result[i+1] - result[i] if result[i+1] - result[i] < max_ else max_
return max_
501 二叉搜索树中的众数

image.png

思路:直接中序遍历,然后字典排序,输出值不为1的键。

注意:如果键对应的值都是最大的,那么都输出,如果键值对个数等于节点个数,也需要都输出。

如下代码可以在力扣上通过,但是时间复杂度很高。

    result = []
    def dfs(node):
        if not node :
            return 
        dfs(node.left)
        result.append(node.val)
        dfs(node.right)
    dfs(root)
    dict_ = {}
    for i in result:
        dict_[i] = dict_.get(i,0) + 1
    max_ = max(dict_.values())
    dict_ = sorted(dict_.items(),key=lambda x:x[1],reverse=True)
    result1 = []
    for i in range(len(dict_)):
        if len(dict_) == len(result):
            result1.append(dict_[i][0])
        elif dict_[i][1] ==  max_:
            result1.append(dict_[i][0])
    return result1

优化之后的代码

    if not root:
        return []
    count_dict = {}
    def dfs(node):
        if not node:
            return
        count_dict[node.val] = count_dict.get(node.val, 0) + 1
        dfs(node.left)
        dfs(node.right)
    dfs(root)
    max_count = max(count_dict.values())
    return [val for val, count in count_dict.items() if count == max_count]

#### 236 二叉树的最近公共祖先

image.png

思路:找到p或者q向上一层返回,就需要用到回溯了,递归是朝下的,回溯是朝上的。


    if not root :
        return 
    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:
        return root
    if left and not right:
        return left
    elif not left and right:
        return right
    else:
        return 

精简版代码:

if root == q or root == p or root is None:
    return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left is not None and right is not None:
    return root
if left is None:
    return right
return left