LintCode Maximum Depth of Binary Tree
1 /** 2 * Definition of TreeNode: 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left, right; 6 * public TreeNode(int val) { 7 * this.val = val; 8 * this.left = this.right = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param root: The root of binary tree. 15 * @return: An integer. 16 */ 17 public int maxDepth(TreeNode root) { 18 // write your code here 19 if (root == null) { 20 return 0; 21 } 22 int left = maxDepth(root.left); 23 int right = maxDepth(root.right); 24 return Math.max(left,right) + 1; 25 } 26 }
This question I used divide and conquer to do this question. I firstly divide this into left and right subproblems and then from the leaves to root return and +1;
浙公网安备 33010602011771号