How to create a simple binary tree (TreeNode)?

To create a simple binary tree, you can follow these steps:

  1. Create a class called TreeNode.
  2. In the TreeNode class, there are three attributes defined: value (the value of the node), left (the left child node), and right (the right child node).
  3. Create a TreeNode object named “root” to serve as the root node of the binary tree.
  4. Add child nodes using the properties of the root object. This can be achieved by creating a new TreeNode object and assigning it to the left or right property.
  5. Repeat step 4 until a complete binary tree is constructed.

Here is an example of a simple binary tree implemented in Python.

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

# 创建根节点
root = TreeNode(1)

# 添加左子节点
root.left = TreeNode(2)

# 添加右子节点
root.right = TreeNode(3)

# 添加左子节点的左子节点
root.left.left = TreeNode(4)

# 添加左子节点的右子节点
root.left.right = TreeNode(5)

This creates a simple binary tree where you can access and manipulate nodes by accessing the root node and its properties.

广告
Closing in 10 seconds
bannerAds