w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
to get all the child count in a gwt tree

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;
    }
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.