二叉树的前、中、后序遍历模板 - 迭代版

前序遍历:

public List preorderTraversal(TreeNode root) {
        ArrayList rs = new ArrayList<>();
        Stack stack = new Stack();
        while(root != null || !stack.isEmpty()){
            if(root != null){
                rs.add(root.val);
                stack.push(root);
                root = root.left;
            }else{
                root = stack.pop();
                root = root.right;
            }
        }
        return rs;
}

中序遍历

    public List inorderTraversal(TreeNode root) {
        ArrayList rs = new ArrayList<>();
        Stack stack = new Stack();
        while(root != null || !stack.isEmpty()){
            if(root != null){
                stack.push(root);
                root = root.left;
            }else{
                root = stack.pop();
                rs.add(root.val);
                root = root.right;
            }
        }
        return rs;
    }

后序遍历

    public List postorderTraversal(TreeNode root) {
        LinkedList l = new LinkedList();
        Stack stack = new Stack();
        while(root != null || !stack.isEmpty()){
            if(root != null){
                l.addFirst(root.val);
                stack.push(root);
                root = root.right;
            }else{
                root = stack.pop();
                root = root.left;
            }
        }
        return new ArrayList(l);
    }

 

你可能感兴趣的:(算法与数据结构)