[BST Medium] 865 Smallest Subtree with all the Deepest Nodes

Description

Given a binary tree rooted at root, the depth of each node is the shortest distance to the root.

A node is deepest if it has the largest depth possible among any node in the entire tree.

The subtree of a node is that node, plus the set of all descendants of that node.

Return the node with the largest depth such that it contains all the deepest nodes in its subtree.

Solution

左右树depth相等即为符合要求的
class Solution(object):
def subtreeWithAllDeepest(self, root):
# Tag each node with it's depth.
depth = {None: -1}
def dfs(node, parent = None):
if node:
depth[node] = depth[parent] + 1
dfs(node.left, node)
dfs(node.right, node)
dfs(root)

    max_depth = max(depth.itervalues())

    def answer(node):
        # Return the answer for the subtree at node.
        if not node or depth.get(node, None) == max_depth:
            return node
        L, R = answer(node.left), answer(node.right)
        return node if L and R else L or R

    return answer(root)

你可能感兴趣的:([BST Medium] 865 Smallest Subtree with all the Deepest Nodes)