数据结构操作模版
程序员文章站
2022-05-18 15:41:33
...
数组遍历
void traverse(int[] arr){
for (int i = 0; i < arr.length; i++ ){
//对arr[i]进行操作
}
}
链表遍历框架
//链表节点
class ListNode{
int value;
ListNode next;
}
//顺序遍历
void traverse(ListNode head){
for (ListNode p = head; p != null; p = p.next){
//对p进行操作
}
}
//递归遍历
void traverse(ListNode head){
traverse(head.next);
}
二叉树遍历框架
import java.util.Stack;
public class Tree {
//树节点定义
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data){
this.value = data;
}
}
//递归先序遍历
public static void preOrderRecur(Node head){
if(head == null){
return;
}
System.out.printf(head.value + " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
//递归中序遍历
public static void InOrderRecur(Node head){
if(head == null){
return;
}
InOrderRecur(head.left);
System.out.printf(head.value + " ");
InOrderRecur(head.right);
}
//递归后续遍历
public static void PostOrderRecur(Node head){
if(head == null){
return;
}
PostOrderRecur(head.left);
PostOrderRecur(head.right);
System.out.println(head.value + " ");
}
//非递归先续遍历
public static void preOrderUnRecur(Node head){
System.out.println("pre-order: ");
if(head != null){
Stack<Node> stack = new Stack<>();
stack.add(head);
if(!stack.isEmpty()){
head = stack.pop();
System.out.println(head.value + " ");
if(head.right != null){
stack.push(head.right);
}
if(head.left != null){
stack.push(head.left);
}
}
}
System.out.println();
}
//非递归中续遍历
public static void InOrderUnRecur(Node head){
System.out.println("in-order: ");
if(head != null) {
Stack<Node> stack = new Stack<>();
while (!stack.isEmpty() || head != null) {
if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
System.out.println(head.value + " ");
head = head.right;
}
}
}
}
//非递归后续遍历
public static void PostOrderUnRecur(Node head){
System.out.println("post-order: ");
if(head != null){
Stack<Node> s1 = new Stack<>();
Stack<Node> s2 = new Stack<>();
s1.push(head);
while (!s1.isEmpty()){
head = s1.pop();
s2.push(head);
if(head.left != null){
s1.push(head.left);
}
if(head.right != null){
s2.push(head.right);
}
}
while (!s2.isEmpty()){
System.out.println(s2.pop().value + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
Node head = new Node(5);
head.left = new Node(3);
head.right = new Node(8);
head.left.left = new Node(2);
head.left.right = new Node(4);
head.left.left.left = new Node(1);
head.right.left = new Node(2);
InOrderRecur(head);
}
}
N叉树遍历框架
class TreeNode{
int val;
TreeNode[] children;
}
void traverse(TreeNode root){
for (TreeNode child : root.children){
//child节点操作
traverse(child);
}
}
N叉树可以扩展成图的遍历,图就是好几个N叉树的结合体。图出现环可以使用布尔数组visited做标记。