java 遍歷所有子節點


/**
 * 
 */
package com.test.controller;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ST2014-12
 *
 */
public class FindAllChildren {
	
	List<Long> childrenIdList=new ArrayList<Long>();
	static List<Node> nodeList=new ArrayList<Node>();
	
	public static void main(String[] args) {
		
		Node node1 = new Node(1l, "蔬菜", 0l);
		Node node2 = new Node(2l, "水產", 0l);
		Node node3 = new Node(3l, "畜牧", 0l);
		Node node4 = new Node(4l, "瓜類", 1l);
		Node node5 = new Node(5l, "葉類", 1l);
		Node node6 = new Node(6l, "絲瓜", 4l);
		Node node7 = new Node(7l, "黃瓜", 4l);
		Node node8 = new Node(8l, "白菜", 5l);
		Node node9 = new Node(9l, "蝦", 2l);
		Node node10 = new Node(10l, "魚", 2l);
		Node node11 = new Node(11l, "牛", 3l);
		
		
		nodeList.add(node1);
		nodeList.add(node2);
		nodeList.add(node3);
		nodeList.add(node4);
		nodeList.add(node5);
		nodeList.add(node6);
		nodeList.add(node7);
		nodeList.add(node8);
		nodeList.add(node9);
		nodeList.add(node10);
		nodeList.add(node11);
		

		FindAllChildren queryCh=new FindAllChildren();	
		
		System.out.println(queryCh.getChildrenId(2l));
	}

	private String getChildrenId(long level) {
		// TODO Auto-generated method stub
        
		List<Node> childrenList=getChildrenList(level);
		//遍歷子節點列表
		queryChildrenList(childrenList);
		
		return childrenIdList.toString();
	}
     //遞歸獲取每個節點下子節點
	void queryChildrenList(List<Node> childrenList){
		
		for(Node n : childrenList){ //遍歷列表中每個節點
		  List<Node>chilList= getChildrenList(n.getId());//獲取每個節點的子節點列表
		  
		  queryChildrenList(chilList);
			
		}
		
	};
	//遍歷全列表 查詢所傳id 下的子節點
	private List<Node> getChildrenList(Long level) {
		List<Node> childrenList=new ArrayList<Node>();//獲取該節點的子節點列表
		// TODO Auto-generated method stub
		for(Node n : nodeList){
			if(n.getParentId()==level){
				childrenList.add(n);
				childrenIdList.add(n.getId());
		 	}			
	 	}
		
		return childrenList;
	 }

     

	}
	

	

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM