94.二叉树的中序遍历

简介: 94.二叉树的中序遍历

image.png


方法一:递归


class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> arraylist=new ArrayList<Integer>();
        if(root==null){
            return arraylist;
        }
        List<Integer> left=inorderTraversal(root.left);
        List<Integer> right=inorderTraversal(root.right);
        arraylist.addAll(left);
        arraylist.add(root.val);
        arraylist.addAll(right);
        return arraylist;
    }
}


方法二:迭代+栈


class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> arraylist=new ArrayList<>();
        if(root==null){
            return arraylist;
        }
        //判断栈是否为空
        Stack<TreeNode> stack=new Stack<TreeNode>();
        TreeNode current=root;
        while(current!=null||!stack.isEmpty()){
            while(current!=null){
                stack.push(current);
                current=current.left;
            }
            current=stack.pop();
            arraylist.add(current.val);
            current=current.right;
        }
        return arraylist;
    }
}
目录
相关文章
|
1月前
二叉树的前序遍历、中序遍历、后序遍历
二叉树的前序遍历、中序遍历、后序遍历
|
8月前
|
存储
|
1月前
|
存储
什么?二叉树的反前序遍历?
什么?二叉树的反前序遍历?
|
1月前
|
算法
二叉树中序遍历(一)
二叉树中序遍历(一)
|
1月前
二叉树的中序遍历
二叉树的中序遍历
15 0
|
1月前
|
C++
二叉树的前序遍历(C++)
二叉树的前序遍历(C++)
31 0
二叉树的前序遍历(C++)
|
1月前
|
C++
二叉树的后序遍历(C++)
二叉树的后序遍历(C++)
28 0
|
1月前
|
Linux
求二叉树的先序遍历
求二叉树的先序遍历
|
1月前
二叉树的前、中、后序遍历的实现
二叉树的前、中、后序遍历的实现