面试准备--二叉树的非递归遍历(Java版)

来源:互联网 发布:缺血半暗带的算法 编辑:程序博客网 时间:2024/05/29 06:28

函数是写在树类中.
前序和中序都是差不多,不过在于输出的顺序而已.
1. 前序在遍历最左节点时,边遍历边输出.
2. 中序在取出栈顶元素和放入右子树之间时输出.

//中序非递归遍历二叉树public ArrayList<Integer> zsort(){        Stack<Node> s = new Stack<Node>();        ArrayList<Integer> q = new ArrayList<Integer>();        Node p;        s.add(root);        while(!s.empty()){            p = s.peek();            while(p!=null){                s.push(p.getLeft());                p = p.getLeft();            }            s.pop();            if(!s.empty()){                p = s.pop();                q.add(p.getData());                s.push(p.getRight());            }        }        return q;    }
//非递归前序遍历二叉树    public ArrayList<Integer> qsort(){        Stack<Node> s = new Stack<Node>();        ArrayList<Integer> q = new ArrayList<Integer>();        Node p;        s.push(root);        while(!s.empty()){            p = s.peek();            while(p!=null){                q.add(p.getData());                s.push(p.getLeft());                p = p.getLeft();            }            s.pop();            if(!s.empty()){                p = s.pop();                s.push(p.getRight());            }        }        return q;    }

后序遍历比较麻烦,要保证左右子树必须在根节点之前遍历输出.遍历根节点的条件:无左右子树或者已经遍历了左右子树(遍历的前一个节点就是左右子树).右子树先进栈,这样在出栈的时候就是左子树先出栈.

//非递归后序遍历二叉树    public ArrayList<Integer> hsort(){        Stack<Node> s = new Stack<Node>();        ArrayList<Integer> q = new ArrayList<Integer>();        Node now = null;        Node pre = null;        s.push(root);        while(!s.empty()){            now = s.peek();            if((now.getLeft() == null && now.getRight() == null) ||                (pre != null &&( pre == now.getLeft() || pre == now.getRight() ) ) ){                q.add(now.getData());                s.pop();                pre = now;            }            else            {                if(now.getRight()!=null){                    s.push(now.getRight());                }                if(now.getLeft()!=null){                    s.push(now.getLeft());                }            }        }        return q;    }
0 0
原创粉丝点击