谷歌面试真题:Descending Tree 的定义与相关函数实现

64次阅读
没有评论

“””
// Write a node class to be used in a tree. A Node should contain exactly one integer and have zero or more children.
“””

“””
Define: a “descending tree” is a tree such that for each node n, the value of n is larger than the value of any descendant of n.

        1000
      /   |   \
   500   200   700
   / \     |     / \
300 100   ...   50  150

Write a function that takes a node which is the root of a tree and determines if it is the root of a descending tree.
“””

“””
Write a function that takes a node which is the root of a descending tree, and returns the largest leaf value.
“””

这组谷歌面试题首先要求你定义一个树节点类,每个节点包含一个整数并能拥有任意数量的子节点。接着题目定义了“Descending Tree”:从根到任意叶子路径上,父节点的值都必须严格大于后代节点的值。第一个函数要判断给定的根是否满足这一严格下降规则,本质是递归检查所有子节点是否都比当前节点小,并且子树本身也满足约束。第二个函数要求在一个合法的 Descending Tree 中找到最大的叶子值,只需遍历所有叶子并比较即可。整个题目考察面向对象设计、树结构的递归处理与正确性判断等核心能力。

正文完
 0