Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
思路1: traverse的方法,就是访问所有的点,然后记录一些信息,从而最后得到全局的信息;
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
private int maxDepth;
/**
* @param root: The root of binary tree.
* @return: An integer
*/
public int maxDepth(TreeNode root) {
maxDepth = 0;
traverse(root, 1);
return maxDepth;
}
public void traverse(TreeNode root, int curDepth){
if(root == null) {
return;
}
maxDepth = Math.max(maxDepth, curDepth);
traverse(root.left, curDepth+1);
traverse(root.right, curDepth+1);
}
}
思路2:divide and conquer,就是分治合的方法,求这一层,怎么通过N-1层的信息推倒而来,然后用最底层的往上走。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer
*/
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}