二叉树的遍历(递归和非递归)

1. 二叉树的遍历

前序遍历:根、左、右
中序遍历:左、根、右
后续遍历:左、右、根

2.递归以及非递归的实现

因为二叉树原本就是递归定义的,所以递归方式实现二叉树的遍历比较简单。非递归方式主要是采用Stack来保存数据,并且由一个current指针指向当前访问的节点。

import java.util.Stack;

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int data){
        val = data;
    }

    public void visit(TreeNode node){
        if(node != null){
            System.out.println(node.val);
        }
    }

    //前序递归遍历
    public void preOrder(TreeNode root){
        if(root != null){
            visit(root);
            preOrder(root.left);
            preOrder(root.right);
        }
    }

    //非递归前序遍历
    public void preOrder_no(TreeNode root){
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode current = root;
        while(current !=null || ! stack.isEmpty()){
            while(current != null){
                visit(current);
                stack.push(current);
                current = current.left;
            }
            if(!stack.isEmpty()){
                TreeNode temp = stack.pop();
                current = temp.right;
            }
        }
    }

    //中序递归遍历
    public void inOrder(TreeNode root){
        if(root != null){
            inOrder(root.left);
            visit(root);
            inOrder(root.right);
        }
    }

    //中序非递归遍历
    public void inOrder_no(TreeNode root){
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode current = root;
        while (current != null || !stack.isEmpty()){
            while(current != null){
                stack.push(current);
                current = current.left;
            }
            if(!stack.isEmpty()){
                TreeNode temp = stack.pop();
                visit(temp);
                current = temp.right;
            }
        }
    }

    //后序递归遍历
    public void postOrder(TreeNode root){
        if(root != null){
            postOrder(root.left);
            postOrder(root.right);
            visit(root);
        }
    }

    // 后续非递归遍历,有一个previsited指针记录访问过的前一个节点
    public void postOrder_no(TreeNode root){
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode current = root;
        TreeNode privisited = null;
        while(current != null || !stack.isEmpty()){
            while(current != null){
                stack.push(current);
                current = current.left;
            }
            current = stack.peek();
            if(current.right == null ||current.right == privisited){
                visit(current);
                stack.pop();
                privisited = current;
                current = null;

            }else{
                current = current.right;
            }
        }
    }

}

    原文作者:风起天蓝
    原文地址: https://www.jianshu.com/p/5325b6d22bf6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞