Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Tree structure

Tree structure

A tree (Tree) is anon-lineardata structure that models the branching hierarchy of trees in nature. Unlike linear structures such as arrays and linked lists, where elements follow one after another, the data elements in a tree (calledNode) have a clear one-to-many hierarchical relationship.

Tree structureJust like a real tree:

Analogies in daily life:

Structure type Search efficiency Insertion efficiency Deletion efficiency Ordering
arrays O(n) O(n) O(n) None
Linked list O(n) O(1) O(1) None
Hash table O(1) O(1) O(1) None
Binary search tree O(log n) O(log n) O(log n) Yes

Basic terminology

Before diving deeper, let's first familiarize ourselves with basic tree terminology:

Basic properties of trees

  1. Unique path: There is exactly one path between any two nodes in a tree.
  2. N nodes, N-1 edges: A tree with N nodes has a total of N-1 edges.
  3. Acyclic: There are no cycles in a tree (i.e., starting from a node and following edges, you can eventually return to it).

Why do we need trees? — Advantages and applications of trees

You might ask, with arrays and linked lists, why do we still need trees? The answer lies in efficiency.

Practical Application Scenarios:


Binary Trees: The most important member of the tree family

A binary tree (Binary Tree) is a tree in which each node has at most two children, usually calledLeft child nodeandRight child node, and it is the foundation of many powerful tree structures (such as binary search trees, heaps, and AVL trees).

The basic structure is as follows:

Basic binary tree terminology

Term define Life Analogy
Node The basic unit containing data and pointers A person in a family
Root Node The top node of a tree An ancestor in a family
Parent node A node with children Parent
Child node A node pointed to by a parent Child
Sibling node Children of the same parent Siblings
Leaf Node A node with no children A person with no children in a family
Depth The number of edges from the root to that node Generation number
Height The number of edges from this node to the farthest leaf node The number of generations the family continues

Binary tree types

Type Feature Time Complexity Application scenarios
Ordinary binary tree Each node has at most 2 children O(n) Expression tree
Full binary tree Every node has either 0 or 2 children O(n) Huffman coding
Complete binary tree Full except for the last level O(n) Heap implementation
Binary search tree Left Average O(log n) Search, sort
Balanced binary tree The height difference between the left and right subtrees is at most 1 O(log n) Database index
Red-black trees Colored balanced tree O(log n) Linux kernel

Binary search tree operations

Operation Description Time Complexity
Find Find a node by value Average O(log n), worst-case O(n)
insert Insert a new node Average O(log n), worst-case O(n)
Delete Delete a specified node Average O(log n), worst-case O(n)
Iteration Visit all nodes O(n)

Binary tree traversal

Traversal refers to visiting every node in a tree according to some rule, with each node visited exactly once. This is the foundation of tree-related algorithms. There are four main ways:

  1. Pre-order traversal (Pre-order):Root -> Left -> Right

  2. First visit the root node, then recursively pre-order traverse the left subtree, and finally recursively pre-order traverse the right subtree.
  3. Apply: Copy a tree, obtain the prefix expression.
  4. - First visit the root node, then recursively pre-order traverse the left subtree, and finally recursively pre-order traverse the right subtree. - **Application**: Copy a tree, obtain the prefix expression.
    1. In-order traversal (In-order):Left -> Root -> Right

    2. First recursively in-order traverse the left subtree, then visit the root node, and finally recursively in-order traverse the right subtree.
    3. Apply: InBinary search treeIn a binary search tree, in-order traversal will output all values inascending orderoutput all values.
    4. - First recursively in-order traverse the left subtree, then visit the root node, and finally recursively in-order traverse the right subtree. - **Application**: In a **binary search tree**, in-order traversal outputs all values in **ascending order**.
      1. Post-order traversal (Post-order):Left -> Right -> Root

      2. First recursively post-order traverse the left subtree, then recursively post-order traverse the right subtree, and finally visit the root node.
      3. Apply: Delete a tree, calculate directory size.
      4. - First recursively post-order traverse the left subtree, then recursively post-order traverse the right subtree, and finally visit the root node. - **Application**: Delete a tree, calculate directory size.
        1. Level-order traversal (Level-order):By level, from left to right

        2. Starting from the root node, visit nodes level by level.
        3. Apply: Process data by hierarchy (such as printing an organizational chart).Usually implemented with the help of a queue (Queue)。
        4. - Starting from the root node, visit nodes level by level. - **Application**: Process data by hierarchy (such as printing an organizational chart). **Usually implemented with the help of a queue (Queue)**.

          Example: For the binary tree shown below, the traversal results are as follows:

          
          
                  1
          
                 / \
          
                2   3
          
               / \   \
          
              4   5   6
          
          

          Practice: Implementing a Binary Tree in Python

          Enough theory, let's get hands-on with code! We'll implement a simple binary tree node class and complete the insertion and traversal operations.

          Step 1: Define the node class

          Each node needs to store data and point to its left and right children.

          Example

          class

          TreeNode:

             

          """Binary tree node class"""

             

          def

          init

          (

          self

          ,

          value

          )

          :

                 

          self

          .

          value

          =

          value  

          The data stored in the node

                 

          self

          .

          left

          =

          None

             

          Points to the left child

                 

          self

          .

          right

          =

          None

           

          Points to the right child

             

          def

          str

          (

          self

          )

          :

                 

          """Convenient for printing node information"""

                 

          return

          f

          "Node({self.value})"

          Step 2: Build a sample tree

          Let's manually build the tree from the example diagram earlier.

          Example

          Create nodes

          root

          =

          TreeNode

          (

          1

          )

          node2

          =

          TreeNode

          (

          2

          )

          node3

          =

          TreeNode

          (

          3

          )

          node4

          =

          TreeNode

          (

          4

          )

          node5

          =

          TreeNode

          (

          5

          )

          node6

          =

          TreeNode

          (

          6

          )

          Build the connections (Links)

          root.

          left

          =

          node2

          root.

          right

          =

          node3

          node2.

          left

          =

          node4

          node2.

          right

          =

          node5

          node3.

          right

          =

          node6

          print

          (

          f

          "Root node: {root}"

          )

          print

          (

          f

          "Left child of root node: {root.left}"

          )

          print

          (

          f

          "Right child of root node: {root.right}"

          )

          Step 3: Implement traversal algorithms (recursive version)

          Recursion is the most intuitive way to implement tree traversal.

          Example

          def

          preorder_traversal

          (

          node

          )

          :

             

          """Pre-order traversal: Root -> Left -> Right"""

             

          if

          node

          is

          None

          :

                 

          return

             

          print

          (

          node.

          value

          ,

          end

          =

          ' '

          )

           

          1. Visit the root node

              preorder_traversal

          (

          node.

          left

          )

           

          2. Traverse the left subtree

              preorder_traversal

          (

          node.

          right

          )

           

          3. Traverse the right subtree

          def

          inorder_traversal

          (

          node

          )

          :

             

          """In-order traversal: Left -> Root -> Right"""

             

          if

          node

          is

          None

          :

                 

          return

              inorder_traversal

          (

          node.

          left

          )

             

          1. Traverse the left subtree

             

          print

          (

          node.

          value

          ,

          end

          =

          ' '

          )

           

          2. Visit the root node

              inorder_traversal

          (

          node.

          right

          )

           

          3. Traverse the right subtree

          def

          postorder_traversal

          (

          node

          )

          :

             

          """Post-order traversal: Left -> Right -> Root"""

             

          if

          node

          is

          None

          :

                 

          return

              postorder_traversal

          (

          node.

          left

          )

           

          1. Traverse the left subtree

              postorder_traversal

          (

          node.

          right

          )

          2. Traverse the right subtree

             

          print

          (

          node.

          value

          ,

          end

          =

          ' '

          )

           

          3. Visit the root node

          print

          (

          "\n--- Traversal Demo ---"

          )

          print

          (

          "Pre-order traversal result:"

          ,

          end

          =

          ' '

          )

          preorder_traversal

          (

          root

          )

          Output: 1 2 4 5 3 6

          print

          (

          "\nIn-order traversal result:"

          ,

          end

          =

          ' '

          )

          inorder_traversal

          (

          root

          )

           

          Output: 4 2 5 1 3 6

          print

          (

          "\nPost-order traversal result:"

          ,

          end

          =

          ' '

          )

          postorder_traversal

          (

          root

          )

          Output: 4 5 2 6 3 1

          Step 4: Implement level-order traversal (using a queue)

          Level-order traversal relies on the "first-in, first-out" property of a queue.

          Example

          from

          collections

          import

          deque

          def

          level_order_traversal

          (

          root

          )

          :

             

          """Level-order traversal: Using a queue"""

             

          if

          root

          is

          None

          :

                 

          return

              queue

          =

          deque

          (

          [

          root

          ]

          )

          Initialize the queue and put the root node in

             

          while

          queue:

                  current_node

          =

          queue.

          popleft

          (

          )

          1. Take a node from the left side of the queue

                 

          print

          (

          current_node.

          value

          ,

          end

          =

          ' '

          )

          2. Visit that node

                 

          3. Add that node's children (if any) to the right side of the queue in order

                 

          if

          current_node.

          left

          :

                      queue.

          append

          (

          current_node.

          left

          )

                 

          if

          current_node.

          right

          :

                      queue.

          append

          (

          current_node.

          right

          )

          print

          (

          "\nLevel-order traversal result:"

          ,

          end

          =

          ' '

          )

          level_order_traversal

          (

          root

          )

          Output: 1 2 3 4 5 6


          Exercises and Challenges

          Congratulations on completing the basics! To truly master trees, hands-on practice is essential.

          Exercise 1: Calculate the height of a tree

          Write a function tree_height(node)that takes the root node of a tree and returns the height of the tree (the height of an empty tree is -1 or 0, whichever convention you prefer; in this example we define it as the number of edges).

          Tip: Tree height = 1 + max(height of the left subtree, height of the right subtree). This is a classic recursion problem.

          Exercise 2: Search for a value in a binary tree

          Write a function search_in_tree(node, target_value), search a given binary tree for whether there exists a node whose value equals target_value . If found, return True; otherwise, returns False。

          Tip: You can use any traversal method, comparing each node's value as you visit it.

          Challenge: Binary Search Tree (BST)

          This is a classic variant of the binary tree. In a binary search tree, for any node:

          Your challenge is:

          1. Create a class that implements insert_into_bst(root, value) function that inserts a value into the correct position in the binary search tree.
          2. Create a class that implements search_in_bst(root, value) function that uses the properties of a BST for efficient search (average time complexity O(log N)).