非递归遍历二叉树

非递归前序遍历

1.申请栈,将头节点压入栈

2.从栈中弹出顶节点,保存值,若右子树不为空,压入右孩子.若左孩子不为空,压入左孩子

3.重复2.直到栈为空

public ArrayList<Integer> preOrderUnRecur(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        if (root == null) {
            return res;
        }
        stack.push(root);
        while (stack.isEmpty() == false) {
            TreeNode cur = stack.pop();
            res.add(cur.val);
            if (cur.right != null) {
                stack.push(cur.right);
            }
            if (cur.left != null) {
                stack.push(cur.left);
            }
        }
        return res;
    }


非递归中序遍历

1.申请栈,将头节点压入栈 , 记作cur节点

2.依次把节点左边界压入栈, cur = cur.left  然后重复 2

3.重复2.直到 cur 为空. 此时从栈中弹出一个节点.记为node   保存值. 然 cur = node.right 重复2.

public ArrayList<Integer> inOrderUnRecur(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        if (root != null) {
            LinkedList<TreeNode> stack = new LinkedList<>();
            while (stack.isEmpty() == false || root != null) {
                if (root != null) {
                    stack.push(root);
                    root = root.left;
                } else {
                    TreeNode cur = stack.pop();
                    res.add(cur.val);
                    root = cur.right;
                }
            }
        }
        return res;
    }

非递归后序遍历

1.申请栈 s1,和s2,将头节点压入s1

2.从s1 弹出节点 cur   把cur 左孩子,右孩子 依次压入s1

3.s1 每弹出一个节点,便压入 s2

4.重复 2, 3.  直到 s1 为空

5.从s2 中 依次弹出节点保存

s1  弹出顺序 为   中 右 左

s2  就是将s1 逆序  弹出顺序 左 右 中  即为后序遍历

public ArrayList<Integer> postOrderUnRecur(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();

        if (root != null) {
            LinkedList<TreeNode> stack1 = new LinkedList<>();
            LinkedList<TreeNode> stack2 = new LinkedList<>();
            stack1.push(root);
            while (stack1.isEmpty() == false) {
                root = stack1.pop();
                stack2.push(root);
                if (root.left != null) {
                    stack1.push(root.left);
                }
                if (root.right != null) {
                    stack1.push(root.right);
                }

                }
                while (stack2.isEmpty() == false) {
                    res.add(stack2.pop().val);
                }
            }

        return res;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值