开发者

Java Tree Debugging

开发者 https://www.devze.com 2023-01-20 02:30 出处:网络
I am trying to implement a method to count all nodes of a tree from the root down. Basically I count the root then add the length of each of the roots child lists.

I am trying to implement a method to count all nodes of a tree from the root down. Basically I count the root then add the length of each of the roots child lists.

       public int size() 
       {
     开发者_运维百科       int count = 1; //count the root node
            for (int i = 0; i < root.getChildren().size(); i++){
                count += (root.getChildren().get(i)).length() + 1;
            }
            return count;
        }

This is the solved solution.


You can implement the size() method as a member of ArrayTreeNode. Use recursion. The size for a node is 1 plus the sum of the children's node sizes.

So inside your size() method you have two cases:

  1. If the node is a leaf, return 1. Here is no recursive call.

  2. If the node has children, call the size() method of all the children, calculate the sum, add 1 for the node and return that value.

Btw. why do you have both tree and root attributes in class ArrayTree? Isn't a root node enough? Why do you have a separate class ArrayTree at all? An ArrayTreeNode for itself is already a tree.

Where do you set the parent attribute of your ArrayTreeNode class? Wouldn't it be best if you set the parent inside the addChild() method to ensure that parent is always valid?

Update:

Ok, you asked for an example. I think if you are not used to recursion it's not so easy to get your head around it.

This is a method of class ArrayTreeNode:

public int size() {
  int sum = 1; // Count at least this node

  // Ask every child for its size. If this node is a leaf,
  // then no recursive call happens.
  // Otherwise call the size() method recursively for ervery 
  // child node. The child's size() method may also call its 
  // own childs size() method, adding another level of recursion.
  // But we can be sure that the recursion comes to an end because 
  // at every leaf the simple answer will be 1. 
  for(ArrayTreeNode<E> child: children) {
    sum += child.size();
  }

  // return our calculated size. 
  return sum;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消