- 结点类
private static class TreeNode { private int value; TreeNode left, right; public TreeNode(int value) { this.value = value; } }
- 构建二叉树
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; }
- 深度优先遍历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); } }
- 广度优先遍历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); } }
- 测试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); } }
- 总结&思考
DFS借助栈数据结构实现;BFS借助队列数据结构实现.
二叉树深度优先遍历和广度优先遍历(Java实现)
最新推荐文章于 2024-05-01 18:18:27 发布