二叉树的递归及非递归遍历

前序遍历

   // 递归前序
    private static void pre(TreeNode root){
        if(root == null){
            return;
        }

        System.out.println(root.val);
        pre(root.left);
        pre(root.right);
    }

    // 非递归前序
    private static void pre1(TreeNode root){
        if(root == null){
            return;
        }

        Stack<TreeNode> s = new Stack<>();
        s.push(root);

        while(!s.isEmpty()){
            TreeNode node = s.pop();
            System.out.println(node.val);

            if(node.right != null){
                s.push(node.right);
            }
            if(node.left != null){
                s.push(node.left);
            }
        }
    }

中序遍历

// 递归中序
    private static void in(TreeNode root){
        if(root == null){
            return;
        }

        in(root.left);
        System.out.println(root.val);
        in(root.right);
    }

    // 非递归中序
    private static void in1(TreeNode root){
        if(root == null){
            return;
        }

        Stack<TreeNode> s = new Stack<>();

        while(!s.isEmpty() || root != null){
            if(root != null){
                s.push(root);
                root = root.left;
            }else{
                root = s.pop();    // 注意,这里要将root指向出栈的元素
                System.out.println(root.val);
                root = root.right;
            }
        }
    }

后序遍历

 // 递归后序遍历
    private static void post(TreeNode root){
        if(root == null){
            return;
        }

        post(root.left);
        post(root.right);
        System.out.println(root.val);
    }

    // 非递归后序遍历
    private static void post1(TreeNode root){
        if(root == null){
            return;
        }

        Stack<TreeNode> s1 = new Stack<>();
        Stack<TreeNode> s2 = new Stack<>();

        s1.push(root);
        while(!s1.isEmpty()){
            TreeNode node = s1.pop();

            s2.push(node);
            if(node.left != null){
                s1.push(node.left);
            }

            if(node.right != null){
                s1.push(node.right);
            }
        }

        while(!s2.isEmpty()){
            TreeNode node = s2.pop();
            System.out.println(node.val);
        }
    }

你可能感兴趣的:(算法基础)