美文网首页
[BST Medium] 865 Smallest Subtre

[BST Medium] 865 Smallest Subtre

作者: Mree111 | 来源:发表于2019-10-24 21:44 被阅读0次

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 Subtre

      本文链接:https://www.haomeiwen.com/subject/cqjtvctx.html