Traversing through a hierarchy to display items as

2019-09-06 17:28发布

问题:

I have a list of items stored as a hierarchy as given below:

FriendList c = 
[ 
    {
        name:"A", 
        nickname:"a", 
        children:[
            {
                name:"A1", 
                nickname:"a1", 
                children:[] 
            },
            {
                name:"A2", 
                nickname:"a2", 
                children:[ 
                    {
                        name:"A21", 
                        nickname:"a21", 
                        children:[] 
                    },
                    {
                        name:"A22", 
                        nickname:"a22", 
                        children:[] 
                    },
                    {
                        name:"A23", 
                        nickname:"a23", 
                        children:[ 
                            {
                                name:"A231", 
                                nickname:"a231", 
                                children:[] 
                            }             
                        ]
                    }
                ]
            },
            {
                name:"A3", 
                nickname:"a3", 
                children:[] 
            },
            {
                name:"A4", 
                nickname:"a4", 
                children:[ 
                    {
                        name:"A41", 
                        nickname:"a41", 
                        children:[] 
                    }
                ]
            }
        ] 
    }
]

I need to display this data using Javascript/ AngularJS on browser and also using Java to generate PDF in the following way:

  parent_name     parent_nickname      child_name      child_nickname

    A                 a                  A1                 a1
    A                 a                  A2                 a2
    A2                a2                 A21                a21
    A2                a2                 A22                a22
    A2                a2                 A23                a23
    A23               a23                A231               a231
    A                 a                  A3                 a3
    A                 a                  A4                 a4
    A4                a4                 A41                a41

current answer displays the structure with first two columns only.

回答1:

What you are asking is just a tree traversing like following (pseudo code) :

void visit(Node node) {
   if (node.children != null) {
      for (Node n : node.children) {
          print(n); // print name and nickname
          visit(n);
      }
   }
}