树的Breadth-First-Search和Depth-First-Search的java实现

假设待搜索的多叉树结构如下:

                              1

                          /    |     \

                        3      5      7

                      /  |  \    |    /   \

                    9   2   4   6  8    10

对应的代码如下:

package com.test.Tree;

import java.util.*;

public class N_aryTree {
	
	Tree tree=null;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		N_aryTree n_aryTree=new N_aryTree();

	}
	
	public N_aryTree() {
		// TODO Auto-generated constructor stub
		Tree tree=new Tree();
		tree.BFS(tree.rootNode, 10);
		tree.DFS(tree.rootNode, 11);
	}

}

class Node{
    public int val;
    public List<Node> children;

    public int getVal() {
		return val;
	}

	public void setVal(int val) {
		this.val = val;
	}

	public List<Node> getChildren() {
		return this.children;
	}

	public void setChildren(List<Node> children) {
		this.children = children;
	}

    public Node(int val) {
        this.val = val;
        this.children = null;
    }
    
}

class Tree{
	Node rootNode;
	Node[] nodes=new Node[10];	
	List<Node> tempChildren=new Vector<Node>();
	List<Node> Children1=new Vector<Node>();
	List<Node> Children2=new Vector<Node>();
	List<Node> Children3=new Vector<Node>();
	List<Node> Children4=new Vector<Node>();
	Queue<Node> childrenQue=new LinkedList<Node>();
	Stack<Node> childrenSta=new Stack<Node>();
	
	public Tree() {
		// TODO Auto-generated constructor stub
		//先给每个节点赋值
		for (int i = 0; i < nodes.length; i++) {
			nodes[i]=new Node(i+1);
		}
		
		//建立节点之间的父子关系
		Children1.add(nodes[8]);		
		Children1.add(nodes[1]);
		Children1.add(nodes[3]);		
		nodes[2].setChildren(Children1);
		
		Children2.add(nodes[5]);
		nodes[4].setChildren(Children2);
		
		Children3.add(nodes[7]);
		Children3.add(nodes[9]);
		nodes[6].setChildren(Children3);

		Children4.add(nodes[2]);
		Children4.add(nodes[4]);
		Children4.add(nodes[6]);
		nodes[0].setChildren(Children4);
		
		rootNode=nodes[0];
		//System.out.println(nodes[2].children.size());

	}
	
	// breadth-first-search,node为待搜索的树的根节点,val为待搜索的节点的值
    public boolean BFS(Node node,int val) {
    	System.out.println("BFS值为"+val+"的节点");
		if (node==null) {
			System.out.println("该树为空");
			return false;
		}		
		System.out.print("搜索路径:");
		if (node.getVal()==val) {
			return true;
		}
		
		childrenQue.offer(node);
/*		for (int i = 0; i < tempChildren.size(); i++) {
			childrenQue.offer(tempChildren.get(i));
		}*/
		
		while (!childrenQue.isEmpty()) {
			///System.out.println("hello");
			Node headNode=childrenQue.poll();
			System.out.print(headNode.getVal()+" ");
			if (headNode.getVal()==val) {
				System.out.println("找到节点");
				return true;
			}
			tempChildren=headNode.getChildren();
			if (tempChildren!=null) {
				for (int i = 0; i < tempChildren.size(); i++) {
					childrenQue.offer(tempChildren.get(i));
				}
			}
/*			for (int i = 0; i < tempChildren.size(); i++) {
				System.out.println("该节点孩子节点的个数为:"+tempChildren.size()+" 第"+(i+1)+
						"个节点的值为:"+tempChildren.get(i).val);
				childrenQue.offer(tempChildren.get(i));
			}*/
		}
		System.out.println("已遍历,该树不包含待寻节点");
		return false;
	}
    
    // depth-first-search,node为待搜索的树的根节点,val为待搜索的节点的值
    public boolean DFS(Node node,int val) {
    	System.out.println("DFS值为"+val+"的节点");
		if (node==null) {
			System.out.println("该树为空");
			return false;
		}
		System.out.print("搜索路径:");
		if (node.getVal()==val) {
			return true;
		}
		
		childrenSta.push(node);
		System.out.print(node.val+" ");
		while (!childrenSta.isEmpty()) {
			Node headNode=childrenSta.peek();
			if (headNode.getChildren()==null||headNode.getChildren().isEmpty()) {
				Node toRmNode=childrenSta.pop();
				if (!childrenSta.isEmpty()) {
					Node fatherNode=childrenSta.peek();
					fatherNode.getChildren().remove(toRmNode);
				}
			}else {
				Node toAddNode=headNode.getChildren().get(0);
				System.out.print(toAddNode.getVal()+" ");
				if (toAddNode.getVal()==val) {
					System.out.println("找到节点");
					return true;
				}
				childrenSta.push(toAddNode);
			}
			
		}
		System.out.println("已遍历,该树不包含待寻节点");
		return false;
	}
    
}

 运行结果:

BFS值为10的节点
搜索路径:1 3 5 7 9 2 4 6 8 10 找到节点
DFS值为11的节点
搜索路径:1 3 9 2 4 5 6 7 8 10 已遍历,该树不包含待寻节点

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值