算法小刷| 随机刷到的好题们

1.排序栈

给定一个乱序的栈,设计一个算法将其升序排列,可以使用一个辅助栈

public class Solution {

    public Stack<Integer> sort(Stack<Integer> stack) {
        int tmp = 0;
        Stack<Integer> tmpStack = new Stack<>();
        while (!stack.isEmpty()) {
            int num = stack.pop();
            if (tmpStack.isEmpty() || tmpStack.peek() < num) {
                tmpStack.add(num);
            } else {
                tmp = num;
                int count = 0;
                while (!tmpStack.isEmpty() && tmpStack.peek() > num) {
                    stack.add(tmpStack.pop());
                    count++;
                }
                tmpStack.add(tmp);
                while (count-- > 0) {
                    tmpStack.add(stack.pop());
                }
            }
        }
        return tmpStack;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        Stack<Integer> stack = new Stack<>();
        stack.add(4);
        stack.add(2);
        stack.add(1);
        stack.add(3);
        Stack<Integer> sort = s.sort(stack);
        while (!sort.isEmpty()) {
            System.out.print(sort.pop());
        }
    }
}

有点像汉诺塔。
在这里插入图片描述

2.从左到右遍历二叉树的叶子节点

public class Solution {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        TreeNode node5 = new TreeNode(5);
        TreeNode node7 = new TreeNode(7);
        TreeNode node10 = new TreeNode(10);
        TreeNode node6 = new TreeNode(6, node5, node7);
        TreeNode node8 = new TreeNode(8, node6, node10);
        List<Integer> leaf = solution.leaf(node8);
        for (Integer i : leaf) {
            System.out.println(i);
        }
        // 输出 5 7 10
    }

    public List<Integer> leaf(TreeNode root) {
        if (root == null) {
            return null;
        }
        List<Integer> res = new ArrayList<>();
        dfs(root, res);
        return res;
    }

    private void dfs(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            res.add(root.val);
        }
        dfs(root.left, res);
        dfs(root.right, res);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值