主要思路:
(1)深度优先搜索DFS;
(2)递归需要考虑的问题(递归结束条件,递归返回值)
(3)算法简单,性能一般。
P.S.当然,这种求深度的题完全可以用广度优先搜索BFS来做,不过需要引入队列,实现起来更容易理解一些。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root){
return helper(root, 0);
}
public int helper(TreeNode root, int depth){
if(root == null) return depth;//递归结束条件
return Math.max(helper(root.left, depth + 1), helper(root.right, depth + 1));//深度优先DFS
}
}
BFS实现:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(NULL),right(NULL) {}
};
//采用BFS的方法,引入队列
int maxDepth(TreeNode *root)
{
if (NULL == root)
return 0;
queue <TreeNode *> que;
int nCount = 1;
int nDepth = 0;// 记录队列里面每一层上的元素
que.push(root);
while(!que.empty()) {
TreeNode *pTemp = que.front();
que.pop();
nCount --;
if (pTemp->left)
que.push(pTemp->left);
if (pTemp->right)
que.push(pTemp->right);
if (nCount == 0) {
nDepth ++;
nCount = que.size();
}
}
return nDepth;
}