其他分享
首页 > 其他分享> > 94.二叉树的中序遍历

94.二叉树的中序遍历

作者:互联网

在这里插入图片描述
方法一:递归

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;
    }
}

标签:right,inorderTraversal,arraylist,List,94,current,二叉树,root,中序
来源: https://blog.csdn.net/qq_43170213/article/details/112851883