class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def add_node(self, value): if self.root is None: self.root = TreeNode(value) else: self._add_node_recursive(self.root, value) def _add_node_recursive(self, node, value): if value < node.value: if node.left is None: node.left = TreeNode(value) else: self._add_node_recursive(node.left, value) else: if node.right is None: node.right = TreeNode(value) else: self._add_node_recursive(node.right, value) def height(self,node): """Returns the height of the longest branch of the tree.""" def height_rec(t): if not t: return 0 else: return max(1+height_rec(t.left), 1+height_rec(t.right)) return height_rec(node)
时间: 2024-02-14 09:20:31 浏览: 91
这段代码实现了二叉树的添加节点和获取二叉树高度的方法。下面是代码的详细解释:
首先定义了 `TreeNode` 类表示二叉树的节点,包含节点的值以及左右子节点。然后定义了 `add_node` 方法用于添加节点到二叉树中。如果树为空,则创建一个新节点作为根节点,否则调用 `_add_node_recursive` 方法将节点添加到正确的位置。
`_add_node_recursive` 方法使用递归实现,比较新节点的值和当前节点的值,如果小于当前节点的值,则递归处理左子树,否则递归处理右子树。如果左子树或右子树为空,则将新节点添加到该位置,否则继续递归处理。
最后定义了 `height` 方法用于获取二叉树的高度,使用了内部的 `height_rec` 方法来递归计算节点的高度。如果节点为空,则返回0,否则分别计算左子树和右子树的高度,并取其中最大值再加上1就是当前节点的高度。
相关问题
# 定义二叉搜索树节点类 class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None # 插入节点 def insert(root, val): if not root: return TreeNode(val) if val < root.val: root.left = insert(root.left, val) else: root.right = insert(root.right, val) return root # 顺序遍历二叉搜索树 def inorderTraversal(root): res = [] if not root: return res res += inorderTraversal(root.left) res.append(root.val) res += inorderTraversal(root.right) return res # 将二叉搜索树转换为双向循环链表 def treeToDoublyList(root): if not root: return None inorder = inorderTraversal(root) head = cur = TreeNode(None) for val in inorder: cur.right = TreeNode(val) cur.right.left = cur cur = cur.right head.right.left = cur cur.right = head.right return head.right # 打印二叉搜索树 def printTree(root, space): if not root: return space += 5 printTree(root.right, space) print(' ' * space, root.val) printTree(root.left, space) # 打印双向循环链表 def printList(head): if not head: return print(head.val, end=' <--> ') cur = head.right while cur != head: print(cur.val, end=' <--> ') cur = cur.right print() # 测试 if __name__ == '__main__': root = None values = [321,34,1443,325,532,321,5,35,36,66] for val in values: root = insert(root, val) bstree = root print('Binary Search Tree:') printTree(bstree, 0) dllist = treeToDoublyList(bstree) print('Doubly Linked List:') printList(dllist)将代码中的value从在代码中输入改为让用户输入
好的,您可以将代码修改如下,让用户输入要插入的节点值:
```
# 定义二叉搜索树节点类
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# 插入节点
def insert(root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
# 顺序遍历二叉搜索树
def inorderTraversal(root):
res = []
if not root:
return res
res += inorderTraversal(root.left)
res.append(root.val)
res += inorderTraversal(root.right)
return res
# 将二叉搜索树转换为双向循环链表
def treeToDoublyList(root):
if not root:
return None
inorder = inorderTraversal(root)
head = cur = TreeNode(None)
for val in inorder:
cur.right = TreeNode(val)
cur.right.left = cur
cur = cur.right
head.right.left = cur
cur.right = head.right
return head.right
# 打印二叉搜索树
def printTree(root, space):
if not root:
return
space += 5
printTree(root.right, space)
print(' ' * space, root.val)
printTree(root.left, space)
# 打印双向循环链表
def printList(head):
if not head:
return
print(head.val, end=' <--> ')
cur = head.right
while cur != head:
print(cur.val, end=' <--> ')
cur = cur.right
print()
# 测试
if __name__ == '__main__':
root = None
values = input('请输入要插入的节点值,以空格分隔:').split()
for val in values:
root = insert(root, int(val))
bstree = root
print('Binary Search Tree:')
printTree(bstree, 0)
dllist = treeToDoublyList(bstree)
print('Doubly Linked List:')
printList(dllist)
```
然后,您可以在运行代码时输入要插入的节点值,以空格分隔,比如:
```
请输入要插入的节点值,以空格分隔:5 4 6 1 2
```
这样,程序就会将这些值插入到二叉搜索树中,并将二叉搜索树转换为双向循环链表,最后输出二叉搜索树和双向循环链表的内容。
class BSTree: """ The binary search tree """ def __init__(self, val): """ Initializae the BSTree """ # Your code here pass def search(self, val): """ Search for a value in the tree, and return the tree node @return: the tree node that contain the val None if val is not in the tree """ # Your code here pass def insert(self, val): """ Insert a value """ # Your code here pass def delete(self, val): """ Delete a value from the tree """ # Your code here pass def toList(self, val): """ Convert tree values into a list in in-order traversal """ # Your code here pass
以下是一个二叉搜索树(Binary Search Tree)的 Python 实现,包括了插入、删除、搜索和转换为列表等方法。
```python
class TreeNode:
"""The tree node class"""
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BSTree:
"""The binary search tree"""
def __init__(self, val):
"""Initialize the BSTree"""
self.root = TreeNode(val)
def search(self, val):
"""Search for a value in the tree, and return the tree node
@return: the tree node that contain the val
None if val is not in the tree
"""
curr_node = self.root
while curr_node:
if curr_node.val == val:
return curr_node
elif curr_node.val > val:
curr_node = curr_node.left
else:
curr_node = curr_node.right
return None
def insert(self, val):
"""Insert a value"""
new_node = TreeNode(val)
if not self.root:
self.root = new_node
return
curr_node = self.root
while curr_node:
if curr_node.val > val:
if curr_node.left:
curr_node = curr_node.left
else:
curr_node.left = new_node
return
else:
if curr_node.right:
curr_node = curr_node.right
else:
curr_node.right = new_node
return
def delete(self, val):
"""Delete a value from the tree"""
def find_min_node(node):
while node.left:
node = node.left
return node
def delete_node(node, val):
if not node:
return None
if node.val == val:
if not node.left and not node.right:
return None
if not node.left:
return node.right
if not node.right:
return node.left
min_node = find_min_node(node.right)
node.val = min_node.val
node.right = delete_node(node.right, min_node.val)
elif node.val > val:
node.left = delete_node(node.left, val)
else:
node.right = delete_node(node.right, val)
return node
self.root = delete_node(self.root, val)
def toList(self):
"""Convert tree values into a list in in-order traversal"""
res = []
def inorder_traversal(node):
if not node:
return
inorder_traversal(node.left)
res.append(node.val)
inorder_traversal(node.right)
inorder_traversal(self.root)
return res
```
使用方法:
```python
bst = BSTree(5)
bst.insert(3)
bst.insert(7)
bst.insert(2)
bst.insert(4)
bst.insert(6)
bst.insert(8)
print(bst.toList()) # [2, 3, 4, 5, 6, 7, 8]
bst.delete(5)
print(bst.toList()) # [2, 3, 4, 6, 7, 8]
node = bst.search(7)
print(node.val) # 7
```
阅读全文