用栈实现的深度优先/广度优先遍历

//深度优先遍历
    private static void getDFS(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode temp = stack.peek();
            System.out.print(temp.value + "\t");
            stack.pop();
            //这里利用了堆的--先进后出的特性,所以右节点要在左节点前入堆,这里如果不好理解建议在Debug下,查看stack的变化内容就比较容易理解了
            if (temp.right != null) {
                stack.push(temp.right);
            }
            if (temp.left != null) {
                stack.push(temp.left);
            }
        }
        System.out.println("深度优先遍历结束");
    }
    ```


    //广度优先遍历
    private static void getBFS(TreeNode root) {
        // TODO Auto-generated method stub
        if (root == null) {
            return;
        }
        ArrayList<TreeNode> queue = new ArrayList<>();
        queue.add(root);
        while (queue.size() > 0) {
            TreeNode temp = queue.get(0);
            queue.remove(0);
            System.out.print(temp.value + "\t");
            //这里利用了队列的--先进先出的特性,所以左节点要在右节点前入堆,这里如果不好理解建议在Debug下,查看stack的变化内容就比较容易理解了
            if (temp.left != null) {
                queue.add(temp.left);
            }
            if (temp.right != null) {
                queue.add(temp.right);
            }
        }
        System.out.println("广度优先遍历结束");
    }
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值