Counting nodes in a tree in Java

前端 未结 15 1748
我寻月下人不归
我寻月下人不归 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

提交回复
热议问题