Counting nodes in a tree in Java

前端 未结 15 1621
我寻月下人不归
我寻月下人不归 2020-12-03 00:03

First of all, I swear this is not homework, it\'s a question I was asked in an interview. I think I made a mess of it (though I did realise the solution requires recursion).

相关标签:
15条回答
  • 2020-12-03 00:23

    Of course, if you want to avoid visiting every node in your tree when you count, and processing time is worth more to you than memory, you can cheat by creating your counts as you build your tree.

    1. Have an int count in each node, initialized to one, which respresents the number of nodes in the subtree rooted in that node.

    2. When you insert a node, before returning from your recursive insert routine, increment the count at the current node.

    i.e.

    public void insert(Node root, Node newNode) {
      if (newNode.compareTo(root) > 1) {
        if (root.right != null) 
          insert(root.right, newNode);
        else
          root.right = newNode;
      } else {
        if (root.left != null)
          insert(root.left, newNode);
        else
          root.left = newNode;
      }
      root.count++;
    }
    

    Then getting the count from any point just involves a lookup of node.count

    0 讨论(0)
  • 2020-12-03 00:24
    int count()
    
    {
       int retval = 1;
        if(null != getRightChild()) retval+=getRightChild().count();
        if(null != getLeftChild()) retval+=getLeftChild().count();
        return retval;
    
    }
    

    God I hope I didn't make a mistake.

    EDIT: I did actually.

    0 讨论(0)
  • 2020-12-03 00:25

    You can count the tree by traversing it many ways. Simply preorder traversal, the code would be (based on the functions you defined):

    int count() {
        count = 1;
        if (this.getLeftChild() != null)
            count += this.getLeftChild().count();
        if (this.getRightChild() != null)
            count += this.getRightChild().count();
        return count;
    }
    
    0 讨论(0)
  • 2020-12-03 00:25

    Implement the method:

    public static int countOneChild(Node root)
    {
        ...
    }
    

    that counts the number of internal nodes in a binary tree having one child. Add the function to tree.java program.

    0 讨论(0)
  • 2020-12-03 00:26

    My first attempt didn't have anything new to add, but then I started to wonder about recursion depth and whether it would be possible to rearrange the code to take advantage of the tail call optimization feature of the latest Java compiler. The main problem was the null test - which can be solved using a NullObject. I'm not sure if TCO can deal with both recursive calls, but it should at least optimize the last one.

    static class NullNode extends Tree {
    
        private static final Tree s_instance = new NullNode();
    
        static Tree instance() {
            return s_instance;
        }
    
        @Override
        Tree getRightChild() {  
            return null;
        }  
    
        @Override
        Tree getLeftChild() {  
            return null;
        }  
    
        int count() {  
            return 0;
        }
    }
    
    int count() {      
        Tree right = getRightChild();      
        Tree left  = getLeftChild();      
    
        if ( right == null ) { right = NullNode.instance(); }
        if ( left  == null ) { left  = NullNode.instance(); }
    
        return 1 + right.count() + left.count();
    }   
    

    The precise implementation of NullNode depends on the implementations used in Tree - if Tree uses NullNode instead of null, then perhaps the child access methods should throw NullPointerException instead of returning null. Anyway, the main idea is to use a NullObject in order to try to benifit from TCO.

    0 讨论(0)
  • 2020-12-03 00:29
    int count() {
      Tree right = getRightChild();
      Tree left = getLeftChild();
      int c = 1;                                      // count yourself!
      if ( right != null ) c += right.count();        // count sub trees
      if ( left != null ) c += left.count();          // ..
      return c;
    }
    
    0 讨论(0)
提交回复
热议问题