题注
我的一个好朋友,Guangyao Miao,当然啦,以前是高中的同班同学,给我推荐了LeetCode这个Online Judge。相比很多第三方的算法测试平台,这个平台我感觉是最友好的,而且很像Coursera给我感觉,有一种大家在一起学习的意思呢。希望能在毕业之前把所有的题目都刷完,毕竟作为一个Cryptographer,不能总是弄那些很理论的东西嘛,得接地气。
第一个题很简单了。
题目
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、如果一个节点是null,那么返回这个节点的depth为0;
2、考察一个节点的左节点和右节点的depth;
3、比较左右节点的depth,取最大值maxDepth,此节点的depth是maxDepth + 1;
确实很简单的思路。
代码
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null){
return 0;
}
int depthLeft = maxDepth(root.left);
int depthRight = maxDepth(root.right);
int depth = 0;
if (depthLeft >= depthRight){
depth = depthLeft + 1;
}else{
depth = depthRight + 1;
}
return depth;
}
}