二叉树遍历(非递归)

package Tree;

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

class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode(int x) { val = x; }
}
public class TreeTraversal {
    //后序遍历
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if(root == null) return res;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode p = root;
        while(!stack.isEmpty() || p != null)
        {
            if(p != null)
            {
                stack.add(p);
                res.add(p.val);
                p = p.right;
            }else
            {
                p = stack.pop().left;
            }
        }
        Collections.reverse(res);
        return res;
    }
    //先序遍历
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if(root == null) return res;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode p = root;
        while(!stack.isEmpty() || p != null)
        {
            if(p != null)
            {
                stack.add(p);
                res.add(p.val);
                p = p.left;
            }else
            {
                p = stack.pop().right;
            }
        }
        return res;
    }
    //中序遍历
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if(root == null) return res;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode p = root;
        while(!stack.isEmpty() || p != null)
        {
            if(p != null)
            {
                stack.add(p);
                p = p.left;
            }else
            {
                p = stack.pop();
                res.add(p.val);
                p = p.right;
            }
        }
        return res;
     }
    public static void main(String[] args) { // TODO Auto-generated method stub } } 
点赞