leetcode刷题记录 94 二叉树的中序遍历

leetcode 94 二叉树的中序遍历

在这里插入图片描述
首先这道题,一般我们会想到用递归来进行中序遍历。这里就不多说了,代码如下:

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {       
        List<Integer>list = new ArrayList<>();
        if(root==null)
            return list;
        helper(root,list);
        return list;
    }
    public static void helper(TreeNode root,List<Integer>list){
        if(root==null)
            return;
        helper(root.left,list);
        list.add(root.val);
        helper(root.right,list);
    } 
}

但既然可以递归遍历树,那我们也可以使用非递归的遍历,于是我采用栈来进行辅助。代码如下:

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {       
        List<Integer>list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur!=null || !stack.isEmpty()){
            while(cur!=null){
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            list.add(cur.val);
            cur = cur.right;
        }
        return list;
    }
   
}

猜你喜欢

转载自blog.csdn.net/weixin_40453090/article/details/108337504