Tree Level by Level, LinkedList

View previous topic View next topic Go down

Tree Level by Level, LinkedList

Post  Admin on Sat Nov 05, 2011 12:29 pm

public ArrayList<LinkedList<TreeNode>> findLevelLinkList(TreeNode root){
int level=0;
ArrayList<LinkedList<TreeNode>> result=new ArrayList<LinkedList<TreeNode>>();
LinkedList<TreeNode> list=new LinkedList<TreeNode>();
list.add(root);
result.add(level,list);
while(true){
list=new ListedList<TreeNode>();
for(int i=0;i<result.get(level).size();i++){
TreeNode n=(TreeNode) result.get(level).get(i);
if(n!=null){
if(n.left!=null) list.add(n.left);
if(n.right!=null) list.add(n.right);
}
if(list.size()>0){
result.add(level+1,list);
}
else{
break;
}
level++;
}
}
return result;
}

Admin
Admin

Posts : 131
Join date : 2011-08-16

View user profile http://codefornongeek.forumotion.com

Back to top Go down

Re: Tree Level by Level, LinkedList

Post  Admin on Mon Nov 21, 2011 3:24 pm

public ArrayList<LinkedList<Node>> levelprint(Node root){
ArrayList<LinkedList<Node>> final=new ArrayList<LinkedList<Node>>();
int level=0;
Queue<Node> q=new Queue<Node>();
q.euqueue(root);
while(!q.isEmpty()){
int size=q.size();
LinkedList<Node> list=new LinkedList<Node>();
for(int i=0;i<size;i++){
Node temp=q.pop();
list.add(temp);
if(temp.leftchild)
q.add(temp.left);
if(temp.rightchild)
q.add(temp.right)

}
final.add(level, list);
level++:
}

}

Admin
Admin

Posts : 131
Join date : 2011-08-16

View user profile http://codefornongeek.forumotion.com

Back to top Go down

View previous topic View next topic Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum