递归树

package test;

import java.util.*;

public class Recursion {

	public static void main(String[] args) {
		List<TestDemo> rightList = new ArrayList<TestDemo>();
		TestDemo right6 = new TestDemo(6, "客户添加", 5);
		TestDemo right7 = new TestDemo(7, "客户删除", 5);
		TestDemo right8 = new TestDemo(8, "客户修改", 5);
		TestDemo right5 = new TestDemo(5, "客户管理", 0);
		TestDemo right10 = new TestDemo(10, "VIP客户添加", 6);
		TestDemo right11 = new TestDemo(11, "普通客户添加", 6);
		rightList.add(right6);
		rightList.add(right7);
		rightList.add(right8);
		rightList.add(right10);
		rightList.add(right5);
		rightList.add(right11);
		TestDemo root = getRoot(rightList);
		System.out.println(root.toXML());

	}

	public static TestDemo getRoot(List<TestDemo> list) {
		TestDemo root = null;
		for (TestDemo td : list) {
			if (td.getParentId() == 0) {
				root = td;
			}
		}
		initChild(root, list);
		return root;
	}

	// 递归算法
	public static void initChild(TestDemo tdemo, List<TestDemo> list) {
		int parentId = tdemo.getId();
		for (TestDemo td : list) {
			if (td.getParentId() == parentId) {
				tdemo.getChild().add(td);
				initChild(td, list);

			}
		}
	}

}

class TestDemo {
	private int id;
	private String name;
	private int parentId;
	private Set<TestDemo> child = new HashSet<TestDemo>();

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getParentId() {
		return parentId;
	}

	public void setParentId(int parentId) {
		this.parentId = parentId;
	}

	public Set<TestDemo> getChild() {
		return child;
	}

	public void setChild(Set<TestDemo> child) {
		this.child = child;
	}

	public TestDemo(int id, String name, int parentid) {
		this.id = id;
		this.name = name;
		this.parentId = parentid;
	}

	public String toXML() {
		StringBuffer xml = new StringBuffer();
		if (parentId == 0) {
			xml.append("<sx:tree label='" + name + "'>\n");
		} else {
			xml.append("  <sx:treenode lable='" + name + "'>\n");
		}

		for (TestDemo td : child) {
			xml.append(td.toXML());
		}

		if (parentId == 0) {
			xml.append("</sx:tree>\n ");
		} else {
			xml.append("  </sx:treenode>\n");
		}
		return xml.toString();
	}
}

你可能感兴趣的:(递归)