前序遍历 非递归
[java]
public void preordernorec(TreeNode root){
//System.out.println("先序遍历(非递归):");
//用数组模拟栈,假设有节点个数不超过32个
TreeNode[] stack = new TreeNode[32];
for(int i =0;i<32;i++){
stack[i] = null;
}
int index =0;
TreeNode pnode = root;
while(pnode!=null||index>0){
while(pnode!=null){
System.out.print(pnode.getKey()+",");
stack[index++] = pnode;
pnode = pnode.getLeftchlid();
}
pnode = stack[--index];
pnode = pnode.getRightchild();
}
//System.out.println("");
}
public void preordernorec(TreeNode root){
//System.out.println("先序遍历(非递归):");
//用数组模拟栈,假设有节点个数不超过32个
TreeNode[] stack = new TreeNode[32];
for(int i =0;i<32;i++){
stack[i] = null;
}
int index =0;
TreeNode pnode = root;
while(pnode!=null||index>0){
while(pnode!=null){
System.out.print(pnode.getKey()+",");
stack[index++] = pnode;
pnode = pnode.getLeftchlid();
}
pnode = stack[--index];
pnode = pnode.getRightchild();
}
//System.out.println("");
}
前序遍历 递归
[java]
public void preorder(TreeNode root){
if(root!=null){
System.out.print(root.getKey()+",");
preorder(root.getLeftchlid());
preorder(root.getRightchild());
}
}
public void preorder(TreeNode root){
if(root!=null){
System.out.print(root.getKey()+",");
preorder(root.getLeftchlid());
preorder(root.getRightchild());
}
}
中序遍历 非递归
[java]
public void inordernorec(TreeNode root){
TreeNode[] stack = new TreeNode[32];
int index=0;
for(int i =0;i<32;i++){
stack[i] = null;
}
TreeNode pnode = root;
while(pnode!=null||index>0){
while(pnode!=null){
stack[index++] = pnode;
pnode = pnode.getLeftchlid();
}
pnode = stack[--index];
System.out.print(pnode.getKey()+",");
pnode = pnode.getRightchild();
}
//System.out.println("");
}
public void inordernorec(TreeNode root){
TreeNode[] stack = new TreeNode[32];
int index=0;
for(int i =0;i<32;i++){
stack[i] = null;
}
TreeNode pnode = root;
while(pnode!=null||index>0){
while(pnode!=null){
stack[index++] = pnode;
pnode = pnode.getLeftchlid();
}
pnode = stack[--index];
System.out.print(pnode.getKey()+",");
pnode = pnode.getRightchild();
}
//System.out.println("");
}
中序遍历 递归
[java]
public void inorder(TreeNode root){
if(root!=null){
inorder(root.getLeftchlid());
System.out.print(root.getKey()+",");
inorder(root.getRightchild());
}
}
public void inorder(TreeNode root){
if(root!=null){
inorder(root.getLeftchlid());
System.out.print(root.getKey()+",");
inorder(root.getRightchild());
}
}
后序遍历 非递归
[java]
public void postordernorec(TreeNode root){
TreeNode[] stack = new TreeNode[32];
int index=0;
for(int i =0;i<32;i++){
stack[i] = null;
}
TreeNode pnode = root;
TreeNode LastVisit = null;
while(pnode!=null||index>0){
while(pnode!=null){
stack[index++] = pnode;
pnode = pnode.getLeftchlid();
}
pnode=stack[index-1];
if(pnode.getRightchild()==null||pnode.getRightchild()==LastVisit){
System.out.print(pnode.getKey()+",");
LastVisit = pnode;
index--;
pnode = null;
}
else
{
pnode = pnode.getRightchild();
}
}
}
public void postordernorec(TreeNode root){
TreeNode[] stack = new TreeNode[32];
int index=0;
for(int i =0;i<3
补充:软件开发 , Java ,