Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Audrey Lee (UNI al3626) Solution
- // To be run with TreeNode.java in the same directory
- // Precondition: There is a Binary tree
- // Postcondition: Depth of the Binary tree
- public class Solution {
- public static int maxDepth(TreeNode root) {
- // Base case: if tree is empty
- if (root== null || (root.getRight() == null && root.getLeft() == null)) return 0;
- int lDepth, rDepth;
- // Depth of the left subtree
- lDepth= maxDepth(root.getLeft());
- // Depth of the right subtree
- rDepth= maxDepth(root.getRight());
- return Math.max(lDepth, rDepth) + 1;
- }
- /********************For Testing Purposes*********************************/
- /*
- public static void main(String[] args){
- //System.out.println("Testing");
- TreeNode root= new TreeNode(0,null,null);
- root.setLeft(new TreeNode(1,null,null));
- root.getLeft().setRight(new TreeNode(1, null, null));
- // Height of left subtree should be 2
- root.setRight(new TreeNode(2, null, null));
- root.getRight().setRight(new TreeNode(2,null,null));
- root.getRight().getRight().setRight(new TreeNode(2,null,null));
- root.getRight().getRight().getRight().setLeft(new TreeNode(2,null,null));
- // Height of right subtree should be 4
- System.out.println(maxDepth(root)); // 4
- }
- */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement