蓝桥杯——先进的多说好树遍历

多 - 树,一般来讲。而二叉树类似的。但是,它可能有叉树结构。分类似在电脑的文件夹。


static class MyTree {
		private Map map = new HashMap();

		public void add(char parent, char child) {
			List<Character> t = (List<Character>) map.get(parent);// child list
			if (t == null) {
				t = new Vector<Character>();
				map.put(parent, t); // 
			}
			t.add(child);
		}

		public List<Character> getChild(char x) {
			return (List<Character>) map.get(x);
		}
	}
	
	//深度优先
	static void Dfs(MyTree tree,char x)
	{
		List<Character> child=tree.getChild(x);
		Stack<Character> stack=new Stack<Character>();
		
		stack.push(x);
		
		while(!stack.isEmpty())
		{
			System.out.print(stack.peek()+" ");
			List<Character> tmp = tree.getChild(stack.pop());
			if(tmp!=null)
			for(int i=0;i<tmp.size();i++)
			{				
				stack.push(tmp.get(tmp.size()-i-1));
			}
		}
		System.out.println();
	}
	
	//广度优先
	static void Bfs(MyTree tree, char x)
	{
		List<Character> t=tree.getChild(x);
		
		List<Character> lst=new Vector<Character>();
		lst.add(x);
		
		while(lst.size()>0)
		{
			System.out.print(lst.get(0)+" ");
			List<Character> tmp=tree.getChild(lst.remove(0));
			if(tmp!=null)
			{
				for(int j=0;j<tmp.size();j++)
					lst.add(tmp.get(j));
			}
		}

		System.out.println();
	}
	
	public static List<String> showTree(MyTree tree, char x) {
		List<Character> t = tree.getChild(x); // get child list

		List<String> r = new Vector<String>();

		if (t == null) {
			r.add("" + x);
			return r;
		}

		for (int i = 0; i < t.size(); i++) {
			List<String> ri = showTree(tree, t.get(i));
			for (int j = 0; j < ri.size(); j++) {
				String pre = "|  ";
				if (j == 0) {
					if (i == 0)
						pre = x + "--";
					else
						pre = "|--";
				} else {
					if (i == ri.size() - 1) 
						pre = "   ";
					else
						pre = "|  ";
				}
				r.add(pre + ri.get(j));
			}
		}

		return r;
	}

	public static void main(String[] args) {
		MyTree a = new MyTree();
		a.add('a', 'b');
		a.add('b', 'e');
		a.add('b', 'f');
		a.add('a', 'c');
		a.add('a', 'd');
		a.add('d', 'g');
		a.add('d', 'i');
		a.add('g', 'h');
		a.add('f', 'j');
		a.add('f', 'k');

		List<String> lst = showTree(a, 'a');
		for (int i = 0; i < lst.size(); i++) {
			System.out.println(lst.get(i));
		}
		
		System.out.println();
		//
		Bfs(a, 'a');
		
		Dfs(a, 'a');

	}


版权声明:本文博主原创文章。博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/gcczhongduan/p/4802540.html