How to build a k ary tree with array implementation in C?

时间:2015-05-12 23:21:12

标签: c arrays algorithm tree

I'm working on an university project about k ary trees in C language. The exercise require to build a k ary tree as list and port it into an array. At the moment I can build the k ary tree as list successfully, now I'm trying to build a k ary tree with array implementation.

Note that the structure of my k ary tree is made up by one child and "k" siblings. FOr example:

 $getBlockedTraffic = {   
        $accessToken = Import-Clixml C:\PSScripts\token
        # The rest of the logic is removed to save space

    }

New-PSSessionConfigurationFile -Path c:\PSScripts\panos.pssc `
                               -Description 'PANOS Delegation EndPoint' `
                               -ExecutionPolicy Restricted `
                               -SessionType RestrictedRemoteServer `
                               -LanguageMode FullLanguage `
                               -FunctionDefinitions @{Name="Get-PANOSBlockedTraffic";ScriptBlock=$getBlockedTraffic; Options="AllScope"}

Unregister-pssessionconfiguration -name FirewallManagement -force
Test-PSSessionConfigurationFile -Path c:\PSScripts\panos.pssc

$secpasswd = ConvertTo-SecureString "pwdHere" -AsPlainText -Force
$sessionCreds = New-Object System.Management.Automation.PSCredential ("domain\user", $secpasswd)

Register-PSSessionConfiguration -Path 'c:\PSScripts\panos.pssc' `
                                -Name FirewallManagement `
                                -ShowSecurityDescriptorUI `
                                -RunAsCredential $sessionCreds `
                                -AccessMode Remote `
                                -Force

So, about array implementation of a k ary tree, I'm thinking to use something like:

4 (root)
.
.
5---6---23---98
    .
    .
    78---53---22---19

...but I don't know how to store eventually child (and siblings) that has a previous child as parent. I hope I've been clear. So, do you have a best approach to implement a k ary tree with array? Can you give me an example?

1 个答案:

答案 0 :(得分:0)

为什么不像通常使用二叉树那样做,在节点结构中放置一个指向其每个子节点的指针,唯一的区别是现在你有k个孩子而不是两个,所以最简单方法可以是将所有子指针存储在指针数组中:

 struct treeNode {
   int              value;
   struct treenode *children[K];
 };

所以要进入第i个孩子,你会这样做:

 child = parent->children[i];