먼저 노드와 트리 데이터 구조를 만듭니다.
Node:
Node(String value)
Tree
Tree(Node node) : Creates a tree with root as node
Node getNode(Node node, String nodeToRetrive) nodeToRetrive will be a child of node
returns null if not found
Node addNode(Node node, String nodeToBeAdded) nodeToBeAdded will be added as a new child of node and the newly added Node would be returned
는 A.
Node root=new Node("A");
Tree tree=new Tree(root);
분할 "_"에서 토큰에 입력 문자열로 루트로 트리를 만듭니다. 예를 들어, "A_AChild_furtherChild"는 "A", "AChild", "furtherChild"로 나뉩니다.
String s="A_AChild_furtherChild";
String[] tokens=s.split("_");
두 번째부터 시작하는 토큰 (이 경우 "아동")을 반복하고 필요한 처리를 수행합니다.
Node node=tree.root; Node n;
for(i=1 ;i <tokens.length; i++){
n=getNode(node,tokens[i]);
if(n==null){
n=addNode(node,tokens[i]);
}
node=n;
}
위의 루프를 사용하여 전체 트리를 구성 할 수 있습니다.
트리의 노드 값을 재귀 적으로 검색하십시오.
public void printTree(Node n, int level){
display level number of spaces and print the value held by Node n.
for(each of the children of n){
printTree(theChild, level+1)
}
}
위의 재귀 적 방법은 처음에 다음과 같은 방법으로 호출 할 수 있습니다 :
printTree(root,0);
어떤 접근 방법을 생각해 봤어? –
가장 일반적인 방법으로 생각하는 것조차 생각조차 할 수 없었습니다. :-( –
유휴 상태의 두뇌에 약간의 압박감을 가하고 작동시켜야합니다. 그리고 몇 가지 접근법을 생각해보십시오. 그러면 누군가가 당신을 도울 수 있습니다. –