数据结构与算法同种算法分别用递归/回溯与栈实现

Posted 九死九歌

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构与算法同种算法分别用递归/回溯与栈实现相关的知识,希望对你有一定的参考价值。

一、阶乘

import java.util.Stack;

public class Main {

	public static int fact1(int n) {
		if (n == 0) return 1;
		else return n * fact1(n-1);
	}

	public static int fact2(int n) {
		int ans = 1;
		Stack<Integer> stack = new Stack<>();
		while (n >= 1) {
			stack.push(n);
			n--;
		}
		while (!stack.isEmpty()) {
			ans *= stack.pop();
		}
		return ans;
	}

	public static void main(String[] args) {
		int n = 3;
		System.out.println(fact1(n));
		System.out.println(fact2(n));
	}

}

二、生成环形链表

import java.util.Stack;

public class Main {

	private static class Node {

		int data;
		Node next;
		Node prev;

		@Override
		public String toString() {
			StringBuilder sb = new StringBuilder();
			Node cur = this;
			for (int i = 0; i < 2 * data + 3; i++) {
				sb.append(cur.data).append(' ');
				cur = cur.next;
			}
			return sb.toString();
		}

		public Node(int data, Node next, Node prev) {
			this.data = data;
			this.next = next;
			this.prev = prev;
		}

		public Node(int data) {
			this.data = data;
		}

	}

	public static Node getCircleNode1(int data) {
		Node node = new Node(data);
		if (data == 1) {
			node.next = node;
			node.prev = node;
		} else {
			Node head = getCircleNode1(data-1);
			Node rear = head.prev;
			node.next = head;
			node.prev = rear;
			rear.next = node;
			head.prev = node;
		}
		return node;
	}

	public static Node getCircleNode2(int data) {
		Node head = new Node(1);
		head.next = head;
		head.prev = head;
		Stack<Integer> stack = new Stack<>();
		while (data > 1) {
			stack.push(data);
			data--;
		}
		while (!stack.isEmpty()) {
			Node rear = head.prev;
			Node node = new Node(stack.pop(), head, rear);
			rear.next = node;
			head.prev = node;
			head = node;
		}
		return head;
	}

	public static void main(String[] args) {
		int n = 6;
		System.out.println(getCircleNode1(n));
		System.out.println(getCircleNode2(n));
	}

}

三、二叉树的遍历

  先写一个树:

import java.util.LinkedList;
import java.util.Queue;

public class TreeNode {

	int val;
	TreeNode left;
	TreeNode right;
	
	@Override
	public String toString() {
		return "" + val;
	}	

	public TreeNode(int val) {
		this.val = val;
	}

	public TreeNode(int val, TreeNode left, TreeNode right) {
		this.val = val;
		this.left = left;
		this.right = right;
	}

	public TreeNode(Integer[] arr) {
		int i=0;
		if (arr[0] == null) throw new IllegalArgumentException();
		this.val = arr[i];
		Queue<TreeNode> queue = new LinkedList<>();
		queue.offer(this);
		while (!queue.isEmpty()) {
			int count = queue.size();
			while (count > 0) {
				TreeNode node = queue.poll();
				count--;
				i++;
				if (arr[i] != null) {
					node.left = new TreeNode(arr[i]);
					queue.add(node.left);
				}
				i++;
				if (arr[i] != null) {
					node.right = new TreeNode(arr[i]);
					queue.add(node.right);
				}
			}
		}
	}

}

1.前序遍历:

import java.util.Stack;

public class Main {

	public static void preorderTraversal1(TreeNode root) {
		if (root != null) {
			System.out.print(root + " ");
			preorderTraversal1(root.left);
			preorderTraversal1(root.right);
		}
	}

	public static void preorderTraversal2(TreeNode root) {
		Stack<TreeNode> stack = new Stack<>();
		while (root != null || !stack.isEmpty()) {
			while (root != null) {
				System.out.print(root.val + " ");
				stack.add(root);
				root = root.left;
			}
			root = stack.pop().right;
		}
		System.out.println();
	}

	public static void main(String[] args) {
		TreeNode root = new TreeNode(new Integer[]{1, 2, 3, null, 4, null, null, null, null});
		preorderTraversal2(root);
		preorderTraversal1(root);
	}

}


2.中序遍历

import java.util.Stack;

public class Main {

	public static void inorderTraversal1(TreeNode root) {
		if (root != null) {
			inorderTraversal1(root.left);
			System.out.print(root + " ");
			inorderTraversal1(root.right);
		}
	}

	public static void inorderTraversal2(TreeNode root) {
		Stack<TreeNode> stack = new Stack<>();
		while (root != null || !stack.isEmpty()) {
			while (root != null) {
				stack.push(root);
				root = root.left;
			}
			TreeNode temp = stack.pop();
			System.out.print(temp + " ");
			root = temp.right;
		}
		System.out.println();
	}

	public static void main(String[] args) {
		TreeNode root = new TreeNode(new Integer[]{1, 2, 3, null, 4, null, null, null, null});
		inorderTraversal2(root);
		inorderTraversal1(root);
	}

}

3.后序遍历

import java.util.Stack;

public class Main {

	public static void postorderTraversal1(TreeNode root) {
		if (root != null) {
			postorderTraversal1(root.left);
			postorderTraversal1(root.right);
			System.out.print(root + " ");
		}
	}

	public static void postorderTraversal2(TreeNode root) {
		Stack<TreeNode> stack = new Stack<>();
		TreeNode prev = null;
		while (root != null || !stack.isEmpty()) {
			while (root != null) {
				stack.push(root);
				root = root.left;
			}
			root = stack.peek();
			if (root.right == null || root.right == prev) {
				System.out.print(root + " ");
				stack.pop();
				prev = root;
				root = null;
			} else {
				root = root.right;
			}
		}
		System.out.println();
	}

	public static void main(String[] args) {
		TreeNode root = new TreeNode(new Integer[]{1, 2, 3, null, 4, null, null, null, null});
		postorderTraversal2(root);
		postorderTraversal1(root);
	}

}

四、走迷宫

  先构造一个工具类

package com.spd;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MazeUtils {

	public static boolean[][] readMaze(String path) {
		boolean[][] maze = null;
		try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)))) {
			int x = Integer.parseInt(br.readLine().split("=")[1]);
			int y = Integer.parseInt(br.readLine().split("=")[1]);
			maze = new boolean[x][y];
			for (int i = 0; i < x; i++) {
				char[] arr = br.readLine().toCharArray();
				for (int j = 0; j < y; j++) {
					if (arr[j] == '0') {
						maze[i][j] = false;
					} else if (arr[j] == '1') {
						maze[i][j] = true;
					} else {
						throw new MazeFormatException("迷宫文件中出现非法字符");
					}
				}
			}
		} catch (IOException e) {
			System.err.println("IO出现异常");
		} catch (NumberFormatException e) {
			throw new MazeFormatException("迷宫文件中未提供迷宫的尺寸或包含非法字符");
		} catch (IndexOutOfBoundsException e) {
			throw new MazeFormatException("迷宫实际上的尺寸与文件中提供的尺寸不符合");
		}
		return maze;
	}

	public static String getString(boolean[][] maze, boolean[][] past) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < maze.length; i++) {
			for (int j = 0; j < maze[0].length; j++) {
				if (past[i][j]) {
					sb.append('░');
				} else {
					sb.append(maze[i][j] ? '█' : '▪');
				采用递归与迭代法思想,分别用java编程去实现欧几里德,斐波那契,牛顿迭代法

数据结构与算法-暴力递归与回溯

算法——八皇后问题(递归回溯实现)

7, java数据结构和算法: 八皇后问题分析和实现 , 递归回溯

7, java数据结构和算法: 八皇后问题分析和实现 , 递归回溯

#yyds干货盘点#数据结构与算法-暴力递归与回溯