前序(先序)遍历
先访问根节点,在访问左孩子,有孩子
//前序遍历 递归
public static void preQianXu(Node root){
//root为根节点
//递归终止条件
if(root == null) return;
//打印根节点
System.out.print(root.value);
//递归调用左孩子,右孩子
preQianXu(root.left);
preQianXu(root.right);
}
//非递归 实现前序遍历
public static void preOrderQianXu(Node root){
if(root == null) return;
//定义一个栈
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
//访问栈中的节点
//因为栈是先进后出的 所有前序的 根>左>右,要按照右 左 根的顺序进栈
Node node = stack.pop();
System.out.print(node.value);//先打印根节点
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}
}
中序遍历
先左孩子,再根节点,最后右孩子
//中序遍历 递归
public static void preZhongXu(Node root){
//递归终止条件
if(root == null) return;
preZhongXu(root.left);
//放在中间打印
System.out.print(root.value);
preZhongXu(root.right);
}
//非递归 实现中序遍历
public static void preOrderZhongXu(Node root) {
//要先找到他的最左节点
if (root == null) return;
Stack<Node> stack = new Stack<>();
Node cur = root;
while (!stack.isEmpty() || cur != null) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
Node node = stack.pop();
System.out.print(node.value);
if(node.right != null) cur = node.right;
}
}
后序遍历
先左孩子,后右孩子,最后根节点
//后序遍历 递归
public static void preHouXu(Node root){
//递归终止条件
if(root == null) return;
preHouXu(root.left);
preHouXu(root.right);
//放在后面打印
System.out.print(root.value);
}
//非递归 实现后续遍历
public static void preOrderHouXu(Node root) {
if(root == null) return;
//需要两个栈
Stack<Node> stack = new Stack<>();
Stack<Node> stack2 = new Stack<>();
//根节点最后打印,还是先拿到跟节点
stack.push(root);
while (!stack.isEmpty()){
Node node = stack.pop();
stack2.push(node);
if(node.left != null) stack.push(node.left);
if(node.right != null) stack.push(node.right);
}
while (!stack2.isEmpty()){
System.out.print(stack2.pop().value);
}
}
层序遍历
按照一层一层的顺序去访问,他是广度优先
使用队列的方式,先进先出
public static void bfs(Node root){
//广度优先
if(root == null) return;
//定义一个队列
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()){
Node node = queue.poll();
System.out.print(node.value);
//分别吧他的左孩子 右孩子加到队列里面
if(node.left!=null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}