Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ความลึกของต้นไม้ N-ary (N-Ary Tree Depth) ใน C++


ปัญหา

หาความลึก (Height/Depth) ของต้นไม้ N-ary (โหนดแต่ละตัวมีลูกได้หลายตัว)

โครงสร้างโหนด

struct Node {
    char data;
    vector<Node*> children;
    Node(char val) : data(val) {}
};

อัลกอริธึม Recursive

  • ถ้า root เป็น NULL → depth = 0
  • วนลูปทุก child หา max depth ของ child แล้ว +1

โปรแกรมตัวอย่าง

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Node {
    char data;
    vector<Node*> children;
    Node(char val) : data(val) {}
};

int depthOfTree(Node* root) {
    if (!root) return 0;
    int maxDepth = 0;
    for (Node* child : root->children)
        maxDepth = max(maxDepth, depthOfTree(child));
    return maxDepth + 1;
}

int main() {
    Node* root = new Node('S');
    root->children = {new Node('O'), new Node('A'), new Node('D'), new Node('N')};
    root->children[0]->children = {new Node('L'), new Node('I')};
    root->children[2]->children = {new Node('R')};
    root->children[3]->children = {new Node('C'), new Node('H'), new Node('I')};
    
    cout << "Depth of N-ary tree: " << depthOfTree(root);
    return 0;
}

ผลลัพธ์

Depth of N-ary tree: 3