Reputation: 193
I am using gwt 2.4 I have a tree widget. I know that getchildcount () method gives the child count. In a case where there is a tree with level 1 as the root and suppose I have one level 2 under this root then getchildcount () on level 1 returns 1.
And in another case, if I have a tree with level 1 as the root level and one level 2 as its child. And if this level 2 inturn has level 3 as its child and this level 3 has level 4 as its child. If I do getchildcount () on level 1 then it still returns count as 1. Is there any method where I can get the count of all children? That is, in this case child count of level 1 should return me 3 taking into account the children of level 2?
Hope I am clear enough
Upvotes: 2
Views: 346
Reputation: 4104
You can use a stack to count all the nodes. That's a depth first tree traversal
import java.util.Stack;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
public void onModuleLoad()
{
Tree tree = new Tree();
TreeItem addTextItemRoot = tree.addTextItem("root");
TreeItem addTextItemLeft = addTextItemRoot.addTextItem("left");
addTextItemRoot.addItem(addTextItemLeft);
TreeItem addTextItemRight = addTextItemRoot.addTextItem("right");
addTextItemRoot.addItem(addTextItemRight);
TreeItem addTextItemLeft1 = addTextItemRoot.addTextItem("left-1");
addTextItemRight.addItem(addTextItemLeft1);
TreeItem addTextItemRight1 = addTextItemRoot.addTextItem("right-1");
addTextItemRight.addItem(addTextItemRight1);
Window.alert("count " + dfs(addTextItemRoot));
RootPanel.get().add(tree);
}
int dfs(TreeItem addTextItemRoot)
{
int count = 0;
Stack<TreeItem> stack = new Stack<TreeItem>();
stack.push(addTextItemRoot);
while(!stack.isEmpty())
{
TreeItem pop = stack.pop();
int childCount = pop.getChildCount();
for(int i=0;i<childCount;i++)
{
TreeItem child = pop.getChild(i);
stack.push(child);
count++;
}
}
return count;
}
}
Upvotes: 2