search
HomeBackend DevelopmentC++The wonderful use of recursion in C++ data structures: implementation of stacks and trees

Application of recursion in C data structures: Stack: Stack is implemented recursively through the last-in-first-out (LIFO) structure. Tree: Tree is implemented recursively through a hierarchical structure, supporting operations such as insertion and depth calculation. Recursion provides a concise and efficient solution for processing nested structures, making the implementation of data structures more intuitive and easier to maintain.

递归在 C++ 数据结构中的妙用:栈和树的实现

The wonderful use of recursion in C data structures: the implementation of stacks and trees

Recursion is a powerful programming technology. It allows functions to call themselves to solve problems. Recursion is very useful in the implementation of data structures, especially for processing tree structures and linear structures.

Recursive implementation of the stack

The stack is a last-in-first-out (LIFO) data structure. We can use recursion to implement the stack, as shown below:

struct Node {
  int data;
  Node* next;
};

class Stack {
private:
  Node* head;

public:
  void push(int data) {
    head = new Node{data, head};
  }

  int pop() {
    if (head == nullptr) {
      throw exception("Stack is empty");
    }
    int data = head->data;
    head = head->next;
    return data;
  }

  bool empty() {
    return head == nullptr;
  }
};

Practical case: printing linked list in reverse order

void printLinkedListInReverseOrder(Node* head) {
  if (head == nullptr) {
    return;
  }

  printLinkedListInReverseOrder(head->next);
  cout << head->data << " ";
}

Recursive implementation of tree

Tree is a hierarchical data structure. We can use recursion to implement the tree, as shown below:

struct Node {
  int data;
  vector<Node*> children;
};

class Tree {
private:
  Node* root;

public:
  void insert(int data) {
    if (root == nullptr) {
      root = new Node{data, {}};
    } else {
      insertHelper(root, data);
    }
  }

private:
  void insertHelper(Node* node, int data) {
    for (auto& child : node->children) {
      if (child == nullptr) {
        child = new Node{data, {}};
        return;
      }
    }

    node->children.push_back(new Node{data, {}});
  }

  void printTree() {
    printTreeHelper(root);
  }

private:
  void printTreeHelper(Node* node) {
    cout << node->data << " ";
    for (auto& child : node->children) {
      printTreeHelper(child);
    }
  }
};

Practical case: Calculate the depth of the binary tree

int calculateTreeDepth(Node* root) {
  if (root == nullptr) {
    return 0;
  }

  int maxDepth = 0;
  for (auto& child : root->children) {
    maxDepth = max(maxDepth, calculateTreeDepth(child));
  }

  return maxDepth + 1;
}

Through recursion, we can implement the stack and sum simply and efficiently Key data structures such as trees. Recursion provides powerful tools for processing complex nested structures, making the implementation of data structures more intuitive and easier to maintain.

The above is the detailed content of The wonderful use of recursion in C++ data structures: implementation of stacks and trees. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C   Interview Questions and Answers: Ace Your Next Technical AssessmentC Interview Questions and Answers: Ace Your Next Technical AssessmentApr 28, 2025 am 12:10 AM

C In interviews, smart pointers are the key tools that help manage memory and reduce memory leaks. 1) std::unique_ptr provides exclusive ownership to ensure that resources are automatically released. 2) std::shared_ptr is used for shared ownership and is suitable for multi-reference scenarios. 3) std::weak_ptr can avoid circular references and ensure secure resource management.

The Future of C  : Adaptations and InnovationsThe Future of C : Adaptations and InnovationsApr 27, 2025 am 12:25 AM

The future of C will focus on parallel computing, security, modularization and AI/machine learning: 1) Parallel computing will be enhanced through features such as coroutines; 2) Security will be improved through stricter type checking and memory management mechanisms; 3) Modulation will simplify code organization and compilation; 4) AI and machine learning will prompt C to adapt to new needs, such as numerical computing and GPU programming support.

The Longevity of C  : Examining Its Current StatusThe Longevity of C : Examining Its Current StatusApr 26, 2025 am 12:02 AM

C is still important in modern programming because of its efficient, flexible and powerful nature. 1)C supports object-oriented programming, suitable for system programming, game development and embedded systems. 2) Polymorphism is the highlight of C, allowing the call to derived class methods through base class pointers or references to enhance the flexibility and scalability of the code.

C# vs. C   Performance: Benchmarking and ConsiderationsC# vs. C Performance: Benchmarking and ConsiderationsApr 25, 2025 am 12:25 AM

The performance differences between C# and C are mainly reflected in execution speed and resource management: 1) C usually performs better in numerical calculations and string operations because it is closer to hardware and has no additional overhead such as garbage collection; 2) C# is more concise in multi-threaded programming, but its performance is slightly inferior to C; 3) Which language to choose should be determined based on project requirements and team technology stack.

C  : Is It Dying or Simply Evolving?C : Is It Dying or Simply Evolving?Apr 24, 2025 am 12:13 AM

C isnotdying;it'sevolving.1)C remainsrelevantduetoitsversatilityandefficiencyinperformance-criticalapplications.2)Thelanguageiscontinuouslyupdated,withC 20introducingfeatureslikemodulesandcoroutinestoimproveusabilityandperformance.3)Despitechallen

C   in the Modern World: Applications and IndustriesC in the Modern World: Applications and IndustriesApr 23, 2025 am 12:10 AM

C is widely used and important in the modern world. 1) In game development, C is widely used for its high performance and polymorphism, such as UnrealEngine and Unity. 2) In financial trading systems, C's low latency and high throughput make it the first choice, suitable for high-frequency trading and real-time data analysis.

C   XML Libraries: Comparing and Contrasting OptionsC XML Libraries: Comparing and Contrasting OptionsApr 22, 2025 am 12:05 AM

There are four commonly used XML libraries in C: TinyXML-2, PugiXML, Xerces-C, and RapidXML. 1.TinyXML-2 is suitable for environments with limited resources, lightweight but limited functions. 2. PugiXML is fast and supports XPath query, suitable for complex XML structures. 3.Xerces-C is powerful, supports DOM and SAX resolution, and is suitable for complex processing. 4. RapidXML focuses on performance and parses extremely fast, but does not support XPath queries.

C   and XML: Exploring the Relationship and SupportC and XML: Exploring the Relationship and SupportApr 21, 2025 am 12:02 AM

C interacts with XML through third-party libraries (such as TinyXML, Pugixml, Xerces-C). 1) Use the library to parse XML files and convert them into C-processable data structures. 2) When generating XML, convert the C data structure to XML format. 3) In practical applications, XML is often used for configuration files and data exchange to improve development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)