aeroblastt

depthInTree()

Aug 6th, 2018 (edited)
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. The recursive depthInTree() method takes two parameters – an integer key and the root of a tree/subtree – and it returns the depth in that tree/subtree of the node with the specified key. It is a private static method that can only be called from within the class.
  2.  
  3. The separate depth() method is a “wrapper” method that makes the initial call to depthInTree(), passing in the root of the tree as a whole and returning whatever value depthInTree() returns – which will be the depth in the entire tree of the node with the specified key.
  4.  
  5. If the key is not found, the methods return -1.
  6.  
  7. public int depth(int key) {
  8. if (root == null) { // root is the root of the entire tree
  9. return -1;
  10. }
  11.  
  12. return depthInTree(key, root);
  13. }
  14.  
  15. private static int depthInTree(int key, Node root) {
  16. if (key == root.key) {
  17. return 0;
  18. }
  19.  
  20. if (root.left != null) {
  21. int depthInLeft = depthInTree(key, root.left);
  22. if (depthInLeft != -1) {
  23. return depthInLeft + 1;
  24. }
  25. }
  26.  
  27. if (root.right != null) {
  28. int depthInRight = depthInTree(key, root.right);
  29. if (depthInRight != -1) {
  30. return depthInRight + 1;
  31. }
  32. }
  33.  
  34. return -1;
  35. }
  36. For a binary tree with n nodes, what is the time complexity of this algorithm as a function of n in the best case? In the worst case? For the worst case, give two expressions: one for when the tree is balanced, and one for when the tree is not balanced. Give your answers using big-O notation, and explain them briefly.
Add Comment
Please, Sign In to add comment