Thinking:
Use the list to maintain the tree;
ParentNode=root node;
BeginFlag=false;
Through from beginning to end:
The parent of the node==parentNode?
If equal, let beginFlag=true;
If differ, and beginFlag==true, then the table name of the node is most the right side of the node, a node before printing the node, then parentNode=the node, beginFlag=false;
Implementation:
Public class Tree{
Private final ListThe tree=new ArrayList<> (a);
Private class Node {
Private Node parent;
Private T value;
Private Node (the Node's parent, T value) {
Enclosing the parent=parent;
This value=https://bbs.csdn.net/topics/value;
}
Public Node getParent () {
Return the parent;
}
Public T getValue () {
The return value.
}
}
Public void invoke the (int parentIndex, T value) {
//on behalf of the incoming - 1 add root node
If (parentIndex==1) {
Tree. The add (new Node (null value));
} else {
Tree. The tree. The add (new Node (get (parentIndex), value));
}
}
Public int getParentIndex (int index) {
Return tree. IndexOf (tree. Get (index). The parent).
}
Public int size () {
Return the tree. The size ();
}
Public T getNodeValue (int index) {
Return the tree. The get (index). The value;
}
Public static void main (String [] args) {
TreeTreeTest=new Tree<> (a);
//root
TreeTest. Invoke the (1, 0);
//the second
TreeTest. Invoke the (0, 1);
TreeTest. Invoke the (0, 2);
TreeTest. Invoke the (0, 3);
//the third layer
TreeTest. Invoke the (1, 4);
TreeTest. Invoke the (2, 5);
TreeTest. Invoke the (2, 6);
TreeTest. Invoke the (3, 7);
TreeTest. Invoke the (3, 8);
TreeTest. Invoke the (3, 9);
//layer 4
TreeTest. Invoke the (6, 10);
Int parentIndex=1;
Boolean beginFlag=false;
for (int i=0; iIf (treeTest getParentIndex (I)==parentIndex) {
BeginFlag=true;
} else {
If (beginFlag) {
System. The out. Println (treeTest. GetNodeValue (I - 1));
ParentIndex=I - 1;
BeginFlag=false;
}
}
//if it is the last node, then direct print
If (I==treeTest. The size () - 1) {
System. The out. Println (treeTest. GetNodeValue (I));
break;
}
}
}
}
But the method of time complexity is O (n), I want to know is there a better way?