Java版二叉树和多叉树的DFS与BFS

 

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--;
			}
		}
	}

}

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值