class BiTreeNode: def __init__(self, data=None): self.data = data self.l_child = None self.r_child = None class BiTree(object): def __init__(self, root=None): self.r_child = None self.l_child = None self.root = root @classmethod def createBiTree(cls, order): q = LinkQueue() root = BiTreeNode() print("节点个数") bt.nodeCount(bt.root) print() bt = BiTree(root) q.offer(root) for i in range(len(order)): c = order[i] node = q.peek() if node.l_child is None: newNode = BiTreeNode(c) node.l_child = newNode q.offer(newNode) elif node.r_child is None: newNode = BiTreeNode(c) node.r_child = newNode q.offer(newNode) q.poll() return bt def Order(self, root): q = LinkQueue() q.offer(root) while not q.isEmpty(): p = q.poll() print(p.data, end='') if p.l_child is not None: q.offer(p.l_child) if p.r_child is not None: q.offer(p.r_child) def nodeCount(t): count = 0 if t is not None: count += 1 count += nodeCount(t.l_child) count += nodeCount(t.r_child) return count
时间: 2024-02-14 21:05:22 浏览: 95
BiTreeNode3.rar_BiTreeNode3_bitreenode_孩子兄弟
代码中存在两个问题:
1. 在createBiTree方法中,先调用了bt.nodeCount方法,再将root节点传入BiTree类的构造方法中,这会导致nodeCount方法中的t参数为None,从而导致程序抛出异常。
2. nodeCount方法应该是BiTree类的方法,而不是独立的函数。因此,应该将nodeCount方法移动到BiTree类中,并将其改为实例方法。
修改后的代码如下:
```
from queue import Queue
class BiTreeNode:
def __init__(self, data=None):
self.data = data
self.l_child = None
self.r_child = None
class BiTree(object):
def __init__(self, root=None):
self.root = root
@classmethod
def createBiTree(cls, order):
q = Queue()
root = BiTreeNode()
bt = BiTree(root)
q.put(root)
for i in range(len(order)):
c = order[i]
node = q.get()
if node.l_child is None:
newNode = BiTreeNode(c)
node.l_child = newNode
q.put(newNode)
elif node.r_child is None:
newNode = BiTreeNode(c)
node.r_child = newNode
q.put(newNode)
return bt
def Order(self, root):
q = Queue()
q.put(root)
while not q.empty():
p = q.get()
print(p.data, end='')
if p.l_child is not None:
q.put(p.l_child)
if p.r_child is not None:
q.put(p.r_child)
def nodeCount(self, t):
count = 0
if t is not None:
count += 1
count += self.nodeCount(t.l_child)
count += self.nodeCount(t.r_child)
return count
```
修改后的代码中,将nodeCount方法移动到BiTree类中,并将其改为实例方法。同时,将createBiTree方法中的节点计数移动到Order方法中,确保root节点已经被正确初始化。另外,将LinkQueue替换为Python内置的Queue。
阅读全文