zoukankan      html  css  js  c++  java
  • 前序 中序 后序 遍历 递归 非递归算法 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 preorder(TreeNode root){
    		
    		if(root!=null){
    			System.out.print(root.getKey()+",");
    			preorder(root.getLeftchlid());
    			preorder(root.getRightchild());
    		}
    	}


     

    中序遍历 非递归

    	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 inorder(TreeNode root){
    		
    		if(root!=null){
    			
    			inorder(root.getLeftchlid());
    			System.out.print(root.getKey()+",");
    			inorder(root.getRightchild());
    		}
    	}


     

    后序遍历 非递归

    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 postorder(TreeNode root){
    	if(root!=null){
    		postorder(root.getLeftchlid());
    		postorder(root.getRightchild());
    		System.out.print(root.getKey()+",");
    	}
    }


     

  • 相关阅读:
    [大话数据结构]线性表之单链表结构和顺序存储结构
    [大话数据结构]算法
    [C#编程参考]把图像转换为数组的两种实现
    [C#绘图]在半透明矩形上绘制字符串
    [C#绘图]Matrix类
    在C#调用C++的DLL方法(二)生成托管的DLL
    在C#调用C++的DLL方法(一)生成非托管dll
    彻底解决 LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
    修复./mysql/proc
    linux 网络连接数查看方法
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3201141.html
Copyright © 2011-2022 走看看