Java——使用stack实现二叉树的前中后序遍历

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Traversal {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {

    }

    // 栈实现先序遍历
    public static List<Integer> stackPreorder(TreeNode root){
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode pop = stack.pop();
            if (null != pop){
                if (null != pop.right){
                    stack.push(pop.right);
                }
                if (null != pop.left){
                    stack.push(pop.left);
                }
                stack.push(pop);
                stack.push(null); // 用作标记输出
            } else {
                result.add(stack.pop().val);
            }
        }
        return result;
    }

    // 栈实现中序遍历
    public static List<Integer> stackInorder(TreeNode root){
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode pop = stack.pop();
            if (null != pop){
                if (null != pop.right){
                    stack.push(pop.right);
                }
                stack.push(pop);
                stack.push(null);
                if (null != pop.left){
                    stack.push(pop.left);
                }
            } else {
                result.add(stack.pop().val);
            }
        }
        return result;
    }

    // 栈实现后序遍历
    public static List<Integer> stackPostorder(TreeNode root){
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode pop = stack.pop();
            if (null != pop){
                stack.push(pop);
                stack.push(null);
                if (null != pop.right){
                    stack.push(pop.right);
                }
                if (null != pop.left){
                    stack.push(pop.left);
                }
            } else {
                result.add(stack.pop().val);
            }
        }
        return result;
    }
}

你可能感兴趣的:(java,java,开发语言)