import java.util.LinkedList; public class DepthFirstSearchAndBreadthFirstSearch { public static class TreeNode { public int val; public TreeNode left, right; public TreeNode(int val) { this.val = val; this.left = this.right = null; } } public static void main(String[] args) { TreeNode root = new TreeNode(1); TreeNode tmpNode = root; tmpNode.left = new TreeNode(2); tmpNode.right = new TreeNode(3); tmpNode = tmpNode.left; tmpNode.left = new TreeNode(4); tmpNode.right = new TreeNode(5); DepthFirstSearchAndBreadthFirstSearch DFSAndBFS = new DepthFirstSearchAndBreadthFirstSearch(); DFSAndBFS.depthFirstSearch(root); System.out.println(); DFSAndBFS.breadthFirstSearch(root); } private void depthFirstSearch(TreeNode root) { if (root == null) { return; } LinkedList<TreeNode> tmpList = new LinkedList<>(); tmpList.push(root); while (!tmpList.isEmpty()) { TreeNode tmpNode = tmpList.pop(); System.out.println(tmpNode.val); if (tmpNode.right != null) { tmpList.push(tmpNode.right); } if (tmpNode.left != null) { tmpList.push(tmpNode.left); } } } private void breadthFirstSearch(TreeNode root) { if (root == null) { return; } LinkedList<TreeNode> tmpList = new LinkedList<>(); tmpList.offer(root); while (!tmpList.isEmpty()) { TreeNode tmpNode = tmpList.poll(); System.out.println(tmpNode.val); if (tmpNode.left != null) { tmpList.offer(tmpNode.left); } if (tmpNode.right != null) { tmpList.offer(tmpNode.right); } } } }
二叉树深度和广度优先搜索
最新推荐文章于 2023-12-11 22:24:36 发布