Back to 课程

Computer-science_A-level_Cie

0% Complete
0/0 Steps
  1. computers-and-components
    6 主题
  2. logic-gates-and-logic-circuits
    2 主题
  3. central-processing-unit-cpu-architecture
    6 主题
  4. assembly-language-
    4 主题
  5. bit-manipulation
    1 主题
  6. operating-systems
    3 主题
  7. language-translators
    2 主题
  8. data-security
    3 主题
  9. data-integrity
    1 主题
  10. ethics-and-ownership
    3 主题
  11. database-concepts
    3 主题
  12. database-management-systems-dbms-
    1 主题
  13. data-definition-language-ddl-and-data-manipulation-language-dml
    1 主题
  14. computational-thinking-skills
    1 主题
  15. algorithms
    14 主题
  16. data-types-and-records
    2 主题
  17. arrays
    2 主题
  18. files
    1 主题
  19. introduction-to-abstract-data-types-adt
    1 主题
  20. programming-basics
    1 主题
  21. constructs
    2 主题
  22. structured-programming
    1 主题
  23. program-development-life-cycle
    2 主题
  24. program-design-
    2 主题
  25. program-testing-and-maintenance
    3 主题
  26. user-defined-data-types
    1 主题
  27. file-organisation-and-access-
    3 主题
  28. floating-point-numbers-representation-and-manipulation
    3 主题
  29. protocols
    2 主题
  30. circuit-switching-packet-switching
    1 主题
  31. processors-parallel-processing-and-virtual-machines
    5 主题
  32. boolean-algebra-and-logic-circuits
    4 主题
  33. purposes-of-an-operating-system-os
    3 主题
  34. translation-software
    3 主题
  35. encryption-encryption-protocols-and-digital-certificates
    3 主题
  36. artificial-intelligence-ai
    4 主题
  37. recursion
    1 主题
  38. programming-paradigms
    4 主题
  39. object-oriented-programming
    7 主题
  40. file-processing-and-exception-handling
    2 主题
  41. data-representation
    5 主题
  42. multimedia
    3 主题
  43. compression
    2 主题
  44. networks-and-the-internet
    11 主题
课 Progress
0% Complete

Binary trees

What is a binary tree?

  • A binary tree is a rooted tree where every node has a maximum of 2 nodes

  • A binary tree is essentially a graph and therefore can be implemented in the same way

  • You must understand:

    • Tree traversal of a tree data structure

    • Add new data to a tree

    • Remove data from a tree

binary-trees
  • The most common way to represent a binary tree is by storing each node with a left and right pointer

This information is usually implemented using 2D arrays 

binary-trees-2

Tree terminology

Keyword

Definition

Node

An item in a tree

Edge

Connects two nodes together and is also known as a branch or pointer

Root

A single node which does not have any incoming nodes

Child

A node with incoming edges

Parent

A node with outgoing edges

Subtree

A subsection of a tree consisting of a parent and all the children of a parent

Leaf

A node with no children

Traversing

The process of visiting each node in a tree data structure, exactly once

How do you program a tree?

  • In the following example:

    • A tree is represented using a TreeNode structure, which includes:

      • A value field to store the data held in the node

      • A children field to store a collection (e.g. list or array) of child nodes

    • The createTreeNode function is used to initialise a new tree node, setting its value and creating an empty collection for its children

    • The addChild function allows a new child node to be added to a parent node

      • It creates a new TreeNode with the given value and appends it to the parent’s children collection

    • Finally, the createTreeNode function is used to create the root node

      • Additional child nodes are added using the addChild function, allowing a multi-level tree structure to be built with branches and sub-branches

Pseudocode

CLASS TreeNode DECLARE value : STRING DECLARE children : ARRAY OF TreeNode
ENDCLASS FUNCTION createTreeNode(val : STRING) RETURNS TreeNode DECLARE node : TreeNode SET node = NEW TreeNode SET node.value = val SET node.children = [] RETURN node
ENDFUNCTION PROCEDURE addChild(parent : TreeNode, childValue : STRING) DECLARE childNode : TreeNode SET childNode = createTreeNode(childValue) APPEND childNode TO parent.children
ENDPROCEDURE // Example usage
DECLARE root : TreeNode
SET root = createTreeNode("Root") CALL addChild(root, "Child 1")
CALL addChild(root, "Child 2") // Adding a grandchild to Child 1
DECLARE child1 : TreeNode
SET child1 = root.children[0]
CALL addChild(child1, "Grandchild 1.1")

Python

class TreeNode: def __init__(self, value): self.value = value self.children = [] def createTreeNode(val): return TreeNode(val) def addChild(parent, childValue): childNode = createTreeNode(childValue) parent.children.append(childNode) # Example usage
root = createTreeNode("Root") addChild(root, "Child 1")
addChild(root, "Child 2") # Adding a grandchild to "Child 1"
child1 = root.children[0]
addChild(child1, "Grandchild 1.1")

Java

import java.util.ArrayList; class TreeNode { String value; ArrayList<TreeNode> children; // Constructor public TreeNode(String value) { this.value = value; this.children = new ArrayList<>(); }
} public class TreeExample { // Function to create a tree node public static TreeNode createTreeNode(String val) { return new TreeNode(val); } // Function to add a child to a parent node public static void addChild(TreeNode parent, String childValue) { TreeNode childNode = createTreeNode(childValue); parent.children.add(childNode); } public static void main(String[] args) { // Create the root node TreeNode root = createTreeNode("Root"); // Add children to the root addChild(root, "Child 1"); addChild(root, "Child 2"); // Add a grandchild to "Child 1" TreeNode child1 = root.children.get(0); addChild(child1, "Grandchild 1.1"); }
}

Algorithm to traverse a tree structure

Pseudocode – pre-order tree traversal

PROCEDURE traverseTree(node : TreeNode) IF node = NULL THEN RETURN ENDIF OUTPUT node.value FOR EACH child IN node.children DO CALL traverseTree(child) NEXT
ENDPROCEDURE // Call the traversal on the root
CALL traverseTree(root)

Python – pre-order tree traversal

def traverseTree(node): if node is None: return print(node.value) for child in node.children: traverseTree(child) # Call the traversal
traverseTree(root)

Java – pre-order tree traversal

public static void traverseTree(TreeNode node) { if (node == null) { return; } System.out.println(node.value); for (TreeNode child : node.children) { traverseTree(child); }
} // In main:
traverseTree(root);
  • For a tree like:

    Root

    ├── Child 1

    │ └── Grandchild 1.1

    └── Child 2

  • The output will be:

    Root

    Child 1

    Grandchild 1.1

    Child 2

Algorithm to add data to a tree structure

Pseudocode

PROCEDURE addChild(parent : TreeNode, childValue : STRING) DECLARE childNode : TreeNode SET childNode = createTreeNode(childValue) APPEND childNode TO parent.children
ENDPROCEDURE // Usage:
CALL addChild(root, "New Child")

Python

def addChild(parent, childValue): childNode = TreeNode(childValue) parent.children.append(childNode) # Usage:
addChild(root, "New Child")

Java

public static void addChild(TreeNode parent, String childValue) { TreeNode childNode = new TreeNode(childValue); parent.children.add(childNode);
} // Usage in main:
addChild(root, "New Child");
  • These examples all create a new node with the provided value and attach it to the given parent node

  • This approach allows dynamic construction of trees with multiple levels

Algorithm to remove data to a tree structure

Pseudocode

PROCEDURE removeChild(parent : TreeNode, targetValue : STRING) FOR index FROM 0 TO LENGTH(parent.children) - 1 IF parent.children[index].value = targetValue THEN REMOVE parent.children[index] RETURN ENDIF NEXT
ENDPROCEDURE // Usage
CALL removeChild(root, "Child 1")

Python

def removeChild(parent, targetValue): for i in range(len(parent.children)): if parent.children[i].value == targetValue: del parent.children[i] return # Exit after removing first match # Usage:
removeChild(root, "Child 1")

Java

public static void removeChild(TreeNode parent, String targetValue) { for (int i = 0; i < parent.children.size(); i++) { if (parent.children.get(i).value.equals(targetValue)) { parent.children.remove(i); return; // Exit after first match } }
} // Usage in main:
removeChild(root, "Child 1");
  • This only removes the first matching child from the direct children of a node

  • If you want to remove nodes anywhere in the tree, you’d need a recursive version

  • REMOVE and del and .remove() work because the children collection is a list/array

Responses

您的邮箱地址不会被公开。 必填项已用 * 标注