-1

I am working on my assignment of java in which I have given a question from java data structures:

The question is: Find the depth of the tree if total number of nodes are 20.

How can I find this ? Can anyone please help me ??

Alina Anjum
  • 1,178
  • 6
  • 30
  • 53
  • 4
    I don't think this question is appropriate here, due to two reasons: 1. it's unclear what the result should look like, e.g. a number or some java code. 2. if you ask for help for homework then you should explain what you've done so far. Personally. I think these homeworks are for a reason. It helps you if you are thinking about it. Simply learning the results won't cut it. – Tamas Rev May 17 '16 at 15:53
  • I have this assignment in while learning data structures. i also dont have any whether to write the code or anythinh else... Kindly suggest me the code to find the tree depth if number of nodes are given – Alina Anjum May 17 '16 at 16:04

3 Answers3

2

Inputs that are needed before finding the depth of the tree:

  1. Root node and structure of node. Is it a Binary tree ( or a N-ary tree) ?
  2. Total number of nodes(n) , and
    Is the tree K-ary complete-tree(depth = ⌊logk(n)⌋) or full-tree (depth = logk(n))?

In first case, you can traverse till the leaf using DFS and find the depth of tree(i.e.the length of the longest path from root to a leaf).

In second case, it is just a math work.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
  • Can you please elaborate the 1st one please – Alina Anjum May 17 '16 at 16:33
  • Best place to learn about case 1: http://www.geeksforgeeks.org/write-a-c-program-to-find-the-maximum-depth-or-height-of-a-tree/ – Saurav Sahu May 17 '16 at 16:52
  • The other important question to ask is, "Is the tree balanced?" If you have a search tree that isn't automatically balanced when you insert items, if you insert 20 integers in numeric order (1, 2, 3, ...), then your tree's depth will be 20. At that point it's just a linked list with a bunch of empty pointers. – dx_over_dt May 17 '16 at 17:23
1

Without knowing any elaborating information on the class or lessons related to this question. Traversing the tree and counting the depth would be the basic answer. Here is a related topic.

How to calculate the depth of a binary search tree

Community
  • 1
  • 1
Mr00Anderson
  • 854
  • 8
  • 16
1

Yes agree, it's very common topic to be asked.

I guess, your case your tree type may be binary tree, binary tree has fixed structure of nodes. As you see below 1,2,4,8,16.
*
* *
* * * *
In your case your tree depth will be 5. I hope you can write one of many logic. One simple logic is to find the binary representation of input number. For 20 it is 10100. Length of binary representation is length of binary tree.

Gaurava Agarwal
  • 974
  • 1
  • 9
  • 32