二叉树前序、中序、后序遍历的递归和非递归算法

版权声明:未经允许禁止转载 https://blog.csdn.net/weixin_38481963/article/details/87936930

1、前序遍历

//递归算法
public static void preOrder(TreeNode head){
		if(head==null) return ;
	    System.out.println(head.val);
	    preOrder(head.left);
	    preOrder(head.right);
    }
    
//非递归算法    
    public static void PreOrder(TreeNode root){
	    LinkedList<TreeNode> stack = new LinkedList<>();
        stack.add(root);
	    while(!stack.isEmpty()){
	        TreeNode node = stack.removeLast();
            while(node!=null){
                System.out.println(node.val);
                stack.add(node.right);
                node = node.left;
            }
        }
    }

2、中序遍历

//递归算法
public static void inOrder(TreeNode root){
	    if(root==null) return ;
	    inOrder(root.left);
        System.out.println(root.val);
        inOrder(root.right);
    }

//非递归算法
    public static void InOrder(TreeNode node){
	    LinkedList<TreeNode> stack = new LinkedList<>();
        while(node!=null || !stack.isEmpty()){
            while(node != null){
                stack.add(node);
                node = node.left;
            }
            if(!stack.isEmpty()){
                node = stack.removeLast();
                System.out.println(node.val);
                node = node.right;
            }
        }
    }

3、后序遍历

//递归算法
public static void postOrder(TreeNode node){
	    if(node==null) return ;
	    postOrder(node.left);
	    postOrder(node.right);
        System.out.println(node.val);
    }

//非递归算法,数据结构书上思路
    public static void PostOrder(TreeNode node){
	    LinkedList<TreeNode> stack1 = new LinkedList<>();
	    LinkedList<Integer> stack2 = new LinkedList<>();
	    stack1.add(node);
	    stack2.add(0);
	    while(!stack1.isEmpty()){
	        node = stack1.removeLast();
	        int k = stack2.removeLast();
	        if(k==0){
	            stack1.add(node);
	            stack2.add(1);
	            if(node.left!=null){
	                stack1.add(node.left);
	                stack2.add(0);
                }
            }else if(k==1){
	            stack1.add(node);
	            stack2.add(2);
	            if(node.right!=null){
	                stack1.add(node.right);
	                stack2.add(0);
                }
            }else if(k==2){
                System.out.println(node.val);
            }
        }
    }

//非递归算法,双栈法
    public static void PostOrder2(TreeNode node){
	    Stack<TreeNode> stack1 = new Stack<>();
	    Stack<TreeNode> stack2 = new Stack<>();
	    if(node == null) return ;
	    stack1.push(node);
	    while(!stack1.empty()){
	        node = stack1.pop();
	        stack2.push(node);
	        if(node.left!=null){
	            stack1.push(node.left);
            }
            if(node.right!=null){
                stack1.push(node.right);
            }
        }
        while(!stack2.empty()){
            System.out.println(stack2.pop().val);
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_38481963/article/details/87936930