简体   繁体   中英

Method to count the nodes in a tree

I understand how to count the nodes in a binary search tree if your method parameter is the root node, I'm just wondering if there's a way to count them if the method call parameter is a node other than the root?

I originally had:

public int size(BSTNode cur)
{
    if (cur == null)
        return 0;
    return 1 + size(cur.getLeft()) + size(cur.getRight());  
}

This will only work if the node I use in the method call is the root, otherwise it only returns the number of nodes in a subtree, not the entire tree.

If your tree nodes have a link to a parent, you could go up all the way to the root (ie the node that has no parent):

TreeNode node = ...
while (node.parent != null) {
    node = node.parent; // Go up the tree
}
// Now you are at the root, so you can count all nodes

Otherwise, the task is impossible, because there is no way to reach other nodes higher up in the tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM