leetcode-二叉树的中序遍历

class Solution {
    private List<Integer> retlist = new LinkedList<>();
    public List<Integer> inorderTraversal(TreeNode root) {
        //中序遍历,左臂入栈
        TreeNode cur = root;
        Stack<TreeNode> stack = new Stack<>();
        while(cur!=null || !stack.isEmpty()){
            if(cur!=null){
                stack.add(cur);
                cur = cur.left;
            }
            else{
                cur = stack.pop();
                retlist.add(cur.val);
                cur = cur.right;
            }
        }
        return retlist;
    }
}

迭代写法,核心思路就是和以往只有一个stack作为判断依据不同,这次有两个判断依据TreeNode cur和stack。

如果cur不为空,加入stack,将指针指向left,如果为空pop一个,加入返回值,然后指针指向右边

发布了48 篇原创文章 · 获赞 0 · 访问量 4316

猜你喜欢

转载自blog.csdn.net/weixin_41327340/article/details/104089774