二叉树深度优先遍历和广度优先遍历(Java实现)

本文深入探讨了二叉树的构建与遍历方法,详细介绍了深度优先搜索(DFS)和广度优先搜索(BFS)两种核心遍历算法,并通过具体代码实现了这两种算法,帮助读者理解二叉树的基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 结点类
    private static class TreeNode {
            private int value;
            TreeNode left, right;
    
            public TreeNode(int value) {
                this.value = value;
            }
        }

     

  2. 构建二叉树
        private static TreeNode constructTree(int[] arr, int index) {
            TreeNode root = null;
            if (index < arr.length) {
                int value = arr[index];
                root = new TreeNode(value);
                root.left = constructTree(arr, index*2 + 1);
                root.right = constructTree(arr, index*2 + 2);
                return root;
            }
            return root;
        }

     

  3. 深度优先遍历dfs
        private static void dfs(TreeNode root) {
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            while (!stack.isEmpty()) {
                TreeNode peek = stack.peek();
                System.out.println(peek.value + "\t");
                stack.pop();
    
                if (peek.right != null) stack.push(peek.right);
                if (peek.left != null) stack.push(peek.left);
            }
        }

     

  4. 广度优先遍历bfs
        private static void bfs(TreeNode root) {
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                TreeNode peek = queue.poll();
                System.out.println(peek.value + "\t");
                if (peek.left != null) queue.offer(peek.left);
                if (peek.right != null) queue.offer(peek.right);
            }
        }
    

     

  5. 测试main方法
    public class TreeTraversal {
        public static void main(String[] args) {
            TreeNode root = constructTree(new int[]{1,2,3,4,5,6,7}, 0);
            System.out.println("---dfs---");
            dfs(root);
            System.out.println("---bfs---");
            bfs(root);
        }
    }

     

  6. 总结&思考
    DFS借助栈数据结构实现;BFS借助队列数据结构实现.
Java 中,可以利用递归或栈结构实现 **二叉树深度优先遍历 (DFS)** 队列实现 **广度优先遍历 (BFS)**。以下是详细的说明: --- ### 深度优先遍历(Depth First Search, DFS) #### 实现方式: 1. 前序遍历(Pre-order Traversal):访问根节点 -> 遍历左子树 -> 遍历右子树。 2. 中序遍历(In-order Traversal):遍历左子树 -> 访问根节点 -> 遍历右子树。 3. 后序遍历(Post-order Traversal):遍历左子树 -> 遍历右子树 -> 访问根节点。 **示例代码 - 递归版本** ```java class TreeNode { int val; TreeNode left, right; public TreeNode(int val) { this.val = val; left = null; right = null; } } public class BinaryTreeTraversal { // 前序遍历 void preOrder(TreeNode root) { if (root == null) return; System.out.print(root.val + " "); preOrder(root.left); preOrder(root.right); } // 中序遍历 void inOrder(TreeNode root) { if (root == null) return; inOrder(root.left); System.out.print(root.val + " "); inOrder(root.right); } // 后序遍历 void postOrder(TreeNode root) { if (root == null) return; postOrder(root.left); postOrder(root.right); System.out.print(root.val + " "); } } ``` --- ### 广度优先遍历(Breadth First Search, BFS) #### 实现方式: 通过借助 `Queue` 数据结构逐层访问节点,先从根开始依次处理每一层的所有节点。 **示例代码** ```java import java.util.LinkedList; import java.util.Queue; public class BreadthFirstSearch { void bfs(TreeNode root) { if (root == null) return; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); System.out.print(node.val + " "); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } } } ``` --- ### 总结对比 | 特性 | 深度优先搜索(DFS) | 广度优先搜索(BFS) | |-------------------|---------------------------------------|-------------------------------------| | 使用数据结构 | 栈(系统栈用于递归,手动栈非递归版) | 队列 | | 时间复杂度 | O(n),n为节点数 | O(n) | | 空间复杂度 | 最坏情况O(h), h为树的高度 | 最坏情况O(w), w为最大宽度 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值