94二叉树的中序遍历-迭代

题目描述

给定一个二叉树,返回它的中序 遍历。使用迭代方法。

思路分析

用栈来辅助,先入栈,再访问。

代码实现

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list =new LinkedList<>();
        if(root!=null){
            Stack<TreeNode> stack =new Stack<>();
            while (!stack.isEmpty() || root!=null){
                if(root!=null){
                    stack.push(root);
                    root=root.left;
                }else {
                    root=stack.pop();
                    list.add(root.val);
                    root=root.right;
                }
            }
        }
        return list;
    }
发布了71 篇原创文章 · 获赞 3 · 访问量 2424

猜你喜欢

转载自blog.csdn.net/qq_34761012/article/details/104278358