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++——类 继承
    Pytorch Tensor, Variable, 自动求导
    Python-OpenCV实现二值图像孔洞填充
    神经网络手写数字识别numpy实现
    神经网络反向传播公式推导
    转:Markdown语法大全
    markdown居中对齐,左对齐,右对齐
    硬编码与软编码
    转:Markdown数学公式语法
    Python if __name__=='__main__'
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3201141.html
Copyright © 2011-2022 走看看