深度遍历和广度遍历
<p>深度遍历?</p>
<pre><code> public List&lt;Category&gt; tracedCategoryList(long categoryId) {
List&lt;Category&gt; list = new ArrayList&lt;Category&gt;();
Category bean = categoryDao.getCategoryById(categoryId);
list.add(bean);
long pid = bean.getParent().getId();
while (pid &gt; 0) {
Category temp = categoryDao.getCategoryById(pid);
list.add(temp);
pid = temp.getParent().getId();
}
return list;
}
/**
* 获取子分类
* @param categoryId
* @param recursive 是否递归
* @return
*/
public List&lt;Category&gt; getSubCategoryList(long categoryId, boolean recursive) {
List&lt;Category&gt; list = new ArrayList&lt;Category&gt;();
List&lt;Category&gt; beans = categoryDao.getCategoriesByParent(categoryId);
if (beans != null &amp;&amp; beans.size() &gt; 0) {
list.addAll(beans);
if (recursive) {
for (Category c : beans) {
List&lt;Category&gt; ss = this.getSubCategoryList(c.getId(), true);
if (!ss.isEmpty()) {
list.addAll(ss);
}
}
}
}
return list;
}</code></pre>
<p>广度遍历?</p>
<pre><code> List&lt;Long&gt; list = new ArrayList&lt;Long&gt;();
list.add(id);
for (int i = 0; i &lt; list.size(); ++i) {
List&lt;Category&gt; beans = categoryDao.getCategoriesByParent(list.get(i));
for (Category bean : beans) {
if (newParentId == bean.getId())
throw new ServiceException(ResourceProperty
.getCannotMoveCategoryString());
list.add(bean.getId());
}
}</code></pre>