请为二叉树类binaryTree增加一个功能,统计度数为2的节点个数
时间: 2023-05-31 15:01:41 浏览: 68
class binaryTree:
def __init__(self, value=None, left_child=None, right_child=None):
self.value = value
self.left_child = left_child
self.right_child = right_child
def insert_left(self, value):
if self.left_child is None:
self.left_child = binaryTree(value)
else:
new_node = binaryTree(value)
new_node.left_child = self.left_child
self.left_child = new_node
def insert_right(self, value):
if self.right_child is None:
self.right_child = binaryTree(value)
else:
new_node = binaryTree(value)
new_node.right_child = self.right_child
self.right_child = new_node
def get_left_child(self):
return self.left_child
def get_right_child(self):
return self.right_child
def set_root_value(self, value):
self.value = value
def get_root_value(self):
return self.value
def preorder(self):
print(self.value)
if self.left_child:
self.left_child.preorder()
if self.right_child:
self.right_child.preorder()
def count_degree_2(self):
count = 0
if self.left_child and self.right_child:
count += 1
if self.left_child:
count += self.left_child.count_degree_2()
if self.right_child:
count += self.right_child.count_degree_2()
return count
# 测试代码
tree = binaryTree(1)
tree.insert_left(2)
tree.insert_right(3)
tree.get_left_child().insert_left(4)
tree.get_left_child().insert_right(5)
tree.get_right_child().insert_left(6)
tree.get_right_child().insert_right(7)
print(tree.count_degree_2()) # 输出2,即节点2和节点1是度数为2的节点
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)