参考:https://blog.csdn.net/Gene1994/article/details/85097507
DFS可以使用递归和栈实现;BFS只能使用队列实现。
1 DFS
1.1递归
//DFS递归实现
public void DFSWithRecursion(TreeNode root) {
if (root == null)
return;
if (root.left != null)
DFSWithRecursion(root.left);
if (root.right != null)
DFSWithRecursion(root.right);
}
1.2 栈
//DFS的迭代实现版本(Stack)
public void DFSWithStack(TreeNode root) {
if (root != null)
return;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode treeNode = stack.pop();
if (treeNode.right != null)
stack.push(treeNode.right);
if (treeNode.left != null)
stack.push(treeNode.left);
}
}
2 BFS
//使用Queue实现BFS
public void BFSWithQueue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
if (root != null)
queue.add(root);
while (!queue.isEmpty()) {
TreeNode treeNode = queue.poll();
if (treeNode.left != null)
queue.add(treeNode.left);
if (treeNode.right != null)
queue.add(treeNode.right);
}
}