【发布时间】:2019-04-27 19:59:04
【问题描述】:
最近我有一个关于在二叉树中查找元素的面试问题。我用 C# 编写了递归和迭代解决方案,但问题是在测试用例中,当我们有一个包含 1000000 个节点的树并且所有节点都在左侧时。面试官对我说,我的解决方案(递归和迭代)没有为这种情况节省足够的内存 RAM,我不明白如何改进我的解决方案。
// recusive Mode
public Node Find(int v)
{
if(v == value)
{
return this;
}else if(v <value){
if (left == null) return null;
return left.Find(v);
}else{
if (right == null) return null;
return right.Find(v);
}
}
// iterative
public Node Find(int v)
{
Node current = this;
while(value != v && current != null)
{
if (v < current.value)
{
if (current.left == null){ current = null};
else{current = current.left};
}
else
{
if (current.right == null) { current = null};
else{current = current.right };
}
}
return current;
}
【问题讨论】:
-
无论是迭代还是递归都不会在堆中分配内存。所以我不明白他们如何节省更多的RAM内存。然而,递归版本在每次调用时分配堆栈内存。迭代版本只需要几个字节来保存它的局部变量
Node current -
你的意思是二叉搜索树吧?否则,您的算法将不适用于正常的二叉树。
标签: c# algorithm recursion iteration binary-tree