• 前序 中序 后序 遍历 递归 非递归算法 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()+",");
    	}
    }


     

  • 相关阅读:
    python之约束、加密及logging模块
    python之反射机制与callattr()、issubclass()、isinstance、type()相关
    python之面向对象初识
    python函数名的应用、闭包和迭代器
    python(动态传参、命名空间、函数嵌套、global和nonlocal关键字)
    python中函数的定义、返回值以及参数的简要介绍
    python文件操作
    python中set(集合),深浅拷贝以及一些补充知识点
    python中is与==的区别,编码和解码
    python数据类型:dict(字典)
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3201141.html
Copyright © 2020-2023  润新知