ツリーはjava、再帰、階層ではありません.
3121 ワード
/***前順遍歴*再帰*/
/***前置き遍歴*非再帰*/
後続ループ非再帰
ツリー階層遍歴javaに基づいてツリー階層遍歴を実現する思想は、データ構造キューの先進的な先発機能を借りて、まずルートノードをエンキューし、キューが空でない条件の下でwhileループし、現在のノードはキューヘッダノードであり、それをエンキューしてアクセスし、現在のノードの左ノードが空でなければ左ノードをエンキューし、現在のノードの右ノードが空でない場合は、そのノードをエンキューします.これにより、出番も左から右へ順番に出番することが保証されます.
コードは次のように実装されます.
public void preOrder(BinaryNode Node){
if (Node != null)
{
System.out.print(Node.element + " ");
preOrder(Node.left);
preOrder(Node.right);
}
}
/***前置き遍歴*非再帰*/
public void preOrder1(BinaryNode Node)
{
Stack stack = new Stack<>();
while(Node != null || !stack.empty())
{
while(Node != null)
{
System.out.print(Node.element + " ");
stack.push(Node);
Node = Node.left;
}
if(!stack.empty())
{
Node = stack.pop();
Node = Node.right;
}
}
}
/**
*
*
*/
public void midOrder1(BinaryNode Node)
{
Stack stack = new Stack<>();
while(Node != null || !stack.empty())
{
while (Node != null)
{
stack.push(Node);
Node = Node.left;
}
if(!stack.empty())
{
Node = stack.pop();
System.out.print(Node.element + " ");
Node = Node.right;
}
}
}
後続ループ非再帰
public static void postOrder_Stack(Node root){//
Stack stack = new Stack();
Stack output = new Stack();//
while(node != null || !stack.empty()){
if(node != null){
output.push(node);
stack.push(node);
node = node.right;
}else{
node = stack.pop();
node = node.left;
}
}
while(output.size()>0){
printNode(output.pop());
}
}
ツリー階層遍歴javaに基づいてツリー階層遍歴を実現する思想は、データ構造キューの先進的な先発機能を借りて、まずルートノードをエンキューし、キューが空でない条件の下でwhileループし、現在のノードはキューヘッダノードであり、それをエンキューしてアクセスし、現在のノードの左ノードが空でなければ左ノードをエンキューし、現在のノードの右ノードが空でない場合は、そのノードをエンキューします.これにより、出番も左から右へ順番に出番することが保証されます.
コードは次のように実装されます.
import java.util.LinkedList;
public class LevelOrder
{
public void levelIterator(BiTree root)
{
if(root == null)
{
return ;
}
LinkedList queue = new LinkedList();
BiTree current = null;
queue.offer(root);//
while(!queue.isEmpty())
{
current = queue.poll();//
System.out.print(current.val +"-->");
if(current.left != null)//
{
queue.offer(current.left);
}
if(current.right != null)// ,
{
queue.offer(current.right);
}
}
}
}