二叉树栈实现前中后序遍历(易理解的方法)

说明:首先你需要看懂用栈实现中序遍历的代码,理解其思想:

从根节点开始入栈,找到他的左子树入栈.....一直到他的左子树为空了,左边到头了,取出当前根节点的值,从栈中取出当前根节点

然后找他的右子树继续入栈,找左子树入栈.....,直到右边取完了这时候一个节点就遍历完了,然后继续从栈中取上一个节点继续

其实考虑下为什么用栈呢?就是用他来回溯的要回溯到根节点,对于中序遍历:左中右,我按照右中左的顺序先后入栈里就可以了,然后每次循环取出栈顶节点也就是左子树作为根节点,取他的左右子树入栈,就可以了

实现:

package com.bysj.common.算法;

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

public class 二叉树 {
    static class ColorNode {
        TreeNode node;
        Boolean isContinue;

        public ColorNode(TreeNode node, Boolean isContinue) {
            this.node = node;
            this.isContinue = isContinue;
        }
    }

    public  static List<Integer> inorderTraversal(TreeNode root) {
        if (root == null) {
            return new ArrayList<Integer>();
        }

        List<Integer> res = new ArrayList<>();
        Stack<ColorNode> stack = new Stack<>();
        stack.push(new ColorNode(root, true));

        while (!stack.empty()) {
            ColorNode cn = stack.pop();

            if (cn.isContinue) {
                if (cn.node.right != null) {
                    stack.push(new ColorNode(cn.node.right, true));
                }
                stack.push(new ColorNode(cn.node, false));
                if (cn.node.left != null) {
                    stack.push(new ColorNode(cn.node.left, true));
                }
            } else {
                res.add(cn.node.val);
            }
        }

        return res;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = null;
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(3);
          System.out.println(inorderTraversal(root));
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值