kamyu104 / LintCode

📝 C++11 Solutions of All 289 LintCode Problems (No More Updates)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

wrong solution(subtree.cpp)

coderwoo opened this issue · comments

题目链接:Subtree
解法链接:subtree.cpp

有两个不同大小的二进制树: T1 有上百万的节点; T2 有好几百的节点。请设计一种算法,判定 T2 是否为 T1的子树。

T1有上百万节点,而且并不保证是平衡的,这样直接用递归,会爆栈的吧?lintcode上的测试数据应该很弱吧?如果按照题目所述,又该怎么处理呢?

commented

The idea of my solution is try to traverse all the nodes in the larger tree to match the smaller one.
Thus, the stack it uses to do the traversal would cost at most O(h), where h is the height of the larger tree.

In the normal case, the tree is nearly balanced, thus the height of 10 million nodes is around 24, it is safe to do recursion to traverse all the larger tree.

In the worst case, it would be possibly out of memory if T1 is extremely unbalanced if we just do recursion without any optimization. (the height of the stack would easily exceed 1 million)

But I don't think this problem marked as easy aims to solve this worst case because most of the larger trees in practice are often nearly balanced. If it does mean that, we should focus on how to search a node in a very deep tree (the depth higher than 1 million). It is a harder design problem. The design may be very open. Currently, I have no idea if we don't use extra external space or modify the input data to achieve that. For example, if the data of T1 is not read-only, we could use "Morris Traversal" by modifying the tree node data to track the successor during traversal without using any stack.

Hope anyone could come out a better design for this worst case.
Thanks for your kindness to remind this issue!!