题目:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
思路:
1. 采用分治法
这个方法充分体现的递归的精华。我自己没这么做。
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
2. 遍历(traverse)
每次向下遍历一个节点,深度就加一,到叶节点了就判断下当前深度跟当前最大深度谁大。
public int max = 0;
public int maxDepth(TreeNode root) {
// write your code here
if(root==null){
return 0;
}
dfs(root, 0);
return max;
}
public void dfs(TreeNode root, int dpth){
if(root==null){
max = Math.max(dpth, max);
return;
}
dfs(root.left, dpth+1);
dfs(root.right, dpth+1);
}