Advertisement
sweet1cris

Untitled

Jan 9th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. // Version 1: Divide Conquer
  2. public class Solution {
  3.     public int maxDepth(TreeNode root) {
  4.         if (root == null) {
  5.             return 0;
  6.         }
  7.  
  8.         int left = maxDepth(root.left);
  9.         int right = maxDepth(root.right);
  10.         return Math.max(left, right) + 1;
  11.     }
  12. }
  13.  
  14. // version 2: Traverse
  15. /**
  16.  * Definition of TreeNode:
  17.  * public class TreeNode {
  18.  *     public int val;
  19.  *     public TreeNode left, right;
  20.  *     public TreeNode(int val) {
  21.  *         this.val = val;
  22.  *         this.left = this.right = null;
  23.  *     }
  24.  * }
  25.  */
  26. public class Solution {
  27.     /**
  28.      * @param root: The root of binary tree.
  29.      * @return: An integer.
  30.      */
  31.     private int depth;
  32.    
  33.     public int maxDepth(TreeNode root) {
  34.         depth = 0;
  35.         helper(root, 1);
  36.        
  37.         return depth;
  38.     }
  39.    
  40.     private void helper(TreeNode node, int curtDepth) {
  41.         if (node == null) {
  42.             return;
  43.         }
  44.        
  45.         if (curtDepth > depth) {
  46.             depth = curtDepth;
  47.         }
  48.        
  49.         helper(node.left, curtDepth + 1);
  50.         helper(node.right, curtDepth + 1);
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement