public void DFS(TreeNode root) {深度优先 Stack<TreeNode> stack = new Stack<>(); stack.add(root); while (!stack.isEmpty()) { // 移除最后一个 TreeNode tempNode = stack.pop(); System.out.println(tempNode.element); // 后进先出 if (tempNode.right != null) stack.add(tempNode.right); if (tempNode.left != null) stack.add(tempNode.left); } }
public void BFS(TreeNode root) {广度优先 Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); // 先进先出 while (!queue.isEmpty()) { TreeNode tempTreeNode = queue.remove(); System.out.println(tempTreeNode.element); if (tempTreeNode.left != null) queue.add(tempTreeNode.left); if (tempTreeNode.right != null) queue.add(tempTreeNode.right); } }