力扣—二叉树前中后遍历:递归+迭代

1.前序遍历

1.递归

public List<Integer> preOrder(TreeNode root){
        List<Integer> list = new LinkedList<>();
        if(root==null){
            return list;
        }
        list.add(root.val);
        list.addAll(preOrder(root.left));
        list.addAll(preOrder(root.right));
        return list;
    }

2.迭代

public List<Integer> preOrderLoop(TreeNode root){
        List<Integer> list = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        if(root!=null){
            stack.push(root);
        }

        while(!stack.isEmpty()){
            TreeNode current = stack.pop();
            list.add((Integer) current.val);
            if(current.right!=null){
                stack.push(current.right);
            }
            if(current.left!=null){
                stack.push(current.left);
            }
        }
        return list;
}

2.中序遍历

1.递归

public List<Integer> midOrder(TreeNode root){
        List<Integer> list = new LinkedList<>();
        if(root==null){
            return list;
        }
        list.addAll(midOrder(root.left));
        list.add(root.val);
        list.addAll(midOrder(root.right));

        return list;
    }

2.迭代

public List<Integer> midOrderLoop(TreeNode root){
        List<Integer> list = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode current = root;
        while(current!=null){
            stack.push(current);
            current = current.left;
        }

        while(!stack.isEmpty()){
            TreeNode temp = stack.pop();
            list.add(temp.val);
            TreeNode node = temp.right;
            while(node!=null){
                stack.push(node);
                node = node.left;
            }
        }

        return list;
}

3.后序遍历

1.递归

public List<Integer> backOrder(TreeNode root){
        List<Integer> list = new LinkedList<>();
        if(root==null){
            return list;
        }
        list.addAll(backOrder(root.left));
        list.addAll(backOrder(root.right));
        list.add(root.val);

        return list;
    }

2.迭代

public List<Integer> backOrderLoop(TreeNode root){
        LinkedList<Integer> list = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        if(root!=null){
            stack.push(root);
        }

        while(!stack.isEmpty()){
            TreeNode temp = stack.pop();
            list.addFirst((Integer)temp.val);
            if(temp.left!=null){
                stack.push(temp.left);
            }
            if(temp.right!=null){
                stack.push(temp.right);
            }
        }
        return list;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值