问题描述
我知道以前有人问过这种类型的问题,我不会盲目地问你们这个问题,因为我已经完成了以前的问题,但我完全没有理解。这是下面的代码:
class Node():
def __init__(self,data):
self.data=data
self.left=None
self.right=None
class BST():
def __init__(self):
self.head=None
def insert(self,data):
if self.head is None:
self.head=Node(data)
if self.head:
if data<self.head.data:
if self.head.left is None:
self.head.left=Node(data)
else:
self.head.left.insert(data)
if data>self.head.data:
if self.head.right is None:
self.head.right=Node(data)
else:
self.head.right.insert(data) #Actual error point
l1=BST()
l1.insert(2)
l1.insert(4)
l1.insert(6) #Getting the error while inserting this
我知道我要么需要将 insert
方法放在 Node
类中,要么将 Node
类属性继承到 BST
类中,但我很难实现两种解决方案,你们能不能请我介绍一下这两种解决方案,带有书面代码的解释对我真的很有帮助。
你可能已经厌倦了看到这些问题,你们都是这里的专家,你知道初学者有多难,尤其是我不想从不清楚的概念开始。
解决方法
解决问题的一种方法是根据 public function addtour(Request $request,$id)
{
$tourCheck = DB::table('teckets')->select('tour_id')->where('user_id','=',Auth::user()->id)->paginate(9);
if (in_array($id,$tourCheck))
{
DB::table('tours')->where('id',$id)->update(['counter' => DB::raw('counter +1')]);
$form_data = array('user_id' => $request->input("user_id",auth::user()->id),'tour_id' => $request->input('tour_id',$id),);
tecket::create($form_data);
return view('submit_tour');
}else{
return view('submit_tour')->with('you already get a tecket for this tour');
}
}
的值与其自身值的比较情况,为 Node
提供一种方法来将另一个方法附加到它,并让树 class
调用它。然后树类实例可以调用其头部 Node
来执行此操作。下面的代码展示了如何做到这一点。
值得注意的是,我还更改了树类,通过在创建时将 head
设为具有唯一数据值的 Node
,树类永远不会为空。这样做意味着唯一需要检查空树的时间是在尝试将数据附加到树时引发 TypeError
- 而不是在 {{ 1}} 方法。以这种方式实现它会使代码更简单,运行速度更快。检查是通过查看树的头部是否不是一个不可能是真实数据的特殊值来完成的。
此类特殊值称为“sentinel values”,确保它们与任何可能的合法值区分开来很重要。在 Python 中,您可以创建一个内置(主要是无功能的)object
类的实例来获取一个。
Node.attach()