/**
* BFS:利用队列
*/
public static List<Integer> bfs(TreeNode root) {
Queue<TreeNode> treeNodeQueue = new LinkedList<>();
List<Integer> integerList = new ArrayList<>();
if (root == null) return new ArrayList<>();
((LinkedList<TreeNode>) treeNodeQueue).add(root);
while (!treeNodeQueue.isEmpty()) {
TreeNode treeNode = treeNodeQueue.poll();
integerList.add(treeNode.val);
if (treeNode.left != null) {
((LinkedList<TreeNode>) treeNodeQueue).add(treeNode.left);
}
if (treeNode.right != null) {
((LinkedList<TreeNode>) treeNodeQueue).add(treeNode.right);
}
}
return integerList;
}
/**
* DFS:先序遍历,非递归方式利用 栈
*/
public static List<Integer> dfs(TreeNode root) {
Stack<TreeNode> treeNodeStack = new Stack<>();
List<Integer> integerList = new ArrayList<>();
if (root == null) return new ArrayList<>();
treeNodeStack.add(root);
while (!treeNodeStack.isEmpty()) {
TreeNode treeNode = treeNodeStack.pop();
integerList.add(treeNode.val);
if (treeNode.right != null) treeNodeStack.add(treeNode.right);
if (treeNode.left != null) treeNodeStack.add(treeNode.left);
}
return integerList;
}