二叉搜索树后序遍历的实现-栈与递归

public MyListArray<T> preOrder2() {
        MyListArray<T> list = new MyListArray<>();
        MyStackLinked<NodeTree> stack = new MyStackLinked<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            NodeTree pop = stack.pop();
            list.add(0, pop.value);
            if (pop.left != null) stack.push(pop.left);
            if (pop.right != null) stack.push(pop.right);
        }
        return list;
    }
public MyListArray<T> preOrder3() {
    MyListArray<T> list = new MyListArray<>();
    MyStackLinked<NodeTree> stack = new MyStackLinked<>();
    stack.push(root);
    //先存什么150
    // 1, 定一个中间结点, 赋值根节点
    NodeTree mid = root;
    NodeTree midFather = null;
    while (mid != null) {
        midFather = mid;
        mid = mid.left;
        stack.push(mid);
        //现在stack有1 -100 -150
        //只输出一个
        if (mid == null) {
            mid = midFather.right;
            NodeTree pop = stack.pop();
            list.add(pop.value);
        }
        //走到头了
    }
    //-150  -50  -10  -100  50  170  200  150  100  1

    return list;
}
posted @ 2021-04-06 14:32  花间一壶酒Zz  阅读(70)  评论(0)    收藏  举报