在最深的二叉树中找到元素的最佳解决方案是什么

时间:2018-11-26 07:43:45

标签: c# algorithm recursion iteration binary-tree

最近,我遇到一个访谈问题,它是关于在二叉树中查找元素,我使用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;
     }

我需要一些建议来解决此类问题吗?

1 个答案:

答案 0 :(得分:3)

您的迭代解决方案中包含一些错误。

// iterative
public Node Find(int v)
{
  Node current = this;
  // Here you need to compare current.value instead of just value
  // Also, to use short-circuiting you need to put null-check first
  // otherwise you might access current.value while current is null
  while(current != null && current.value != v)
  {
    if (v < current.value)
    {
       //if (current.left == null){ current = null};
       //else{current = current.left};
       current = current.left; // the same as two commented out lines
    }
    else
    {
      //if (current.right == null) { current = null};
      //else{current = current.right };
      current = current.right; // the same as two commented out lines
    }
  }
  return current;
 }