import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
public class Search {
//二叉树
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){
val = x;
}
}
//多叉树
public class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
}
//--------二叉树---------------
public void dfs(TreeNode root){
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.add(root);
while (!stack.isEmpty()) {
TreeNode tmpNode = stack.peek();
System.out.print(stack.pop());
//先右后左
if (tmpNode.right != null) {
stack.add(tmpNode.right);
}
if (tmpNode.left != null) {
stack.add(tmpNode.left);
}
}
}
public void bfs(TreeNode root){
if (root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode tmpNode = queue.peek();
System.out.print(queue.poll());
if (tmpNode.left != null) {
queue.add(tmpNode.left);
}
if (tmpNode.right != null) {
queue.add(tmpNode.right);
}
}
}
//--------多叉树-----------
public void dfsTree(Node root){
if (root == null) {
return;
}
Stack<Node> stack = new Stack<>();
stack.add(root);
if (!stack.isEmpty()) {
int n = stack.size();
Node tmpNode = stack.peek();
System.out.print(stack.pop());
while (n > 0) {
for (int i = tmpNode.children.size() -1 ; i >= 0 ; i--) {
stack.add(tmpNode.children.get(i));
}
n--;
}
}
}
public void bfsTree(Node root){
if (root == null) {
return;
}
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int n = queue.size();
Node tmpNode = queue.peek();
System.out.print(queue.poll());
while (n > 0) {
for (int i = 0; i < tmpNode.children.size(); i++) {
queue.add(tmpNode.children.get(i));
}
n--;
}
}
}
}