Advertisement
Guest User

Untitled

a guest
Sep 30th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. // Audrey Lee (UNI al3626) Solution
  2.  
  3. // To be run with TreeNode.java in the same directory
  4.  
  5. // Precondition: There is a Binary tree
  6. // Postcondition: Depth of the Binary tree
  7. public class Solution {
  8.  
  9. public static int maxDepth(TreeNode root) {
  10. // Base case: if tree is empty
  11. if (root== null || (root.getRight() == null && root.getLeft() == null)) return 0;
  12. int lDepth, rDepth;
  13.  
  14. // Depth of the left subtree
  15. lDepth= maxDepth(root.getLeft());
  16. // Depth of the right subtree
  17. rDepth= maxDepth(root.getRight());
  18.  
  19. return Math.max(lDepth, rDepth) + 1;
  20. }
  21.  
  22. /********************For Testing Purposes*********************************/
  23. /*
  24. public static void main(String[] args){
  25. //System.out.println("Testing");
  26. TreeNode root= new TreeNode(0,null,null);
  27.  
  28. root.setLeft(new TreeNode(1,null,null));
  29. root.getLeft().setRight(new TreeNode(1, null, null));
  30. // Height of left subtree should be 2
  31.  
  32. root.setRight(new TreeNode(2, null, null));
  33. root.getRight().setRight(new TreeNode(2,null,null));
  34. root.getRight().getRight().setRight(new TreeNode(2,null,null));
  35. root.getRight().getRight().getRight().setLeft(new TreeNode(2,null,null));
  36. // Height of right subtree should be 4
  37.  
  38. System.out.println(maxDepth(root)); // 4
  39. }
  40. */
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement