最近看了点动态规划,二叉树的深度用递归方法解决,算得上是动态规划,不过由于二叉树比较简单,因此不需要应用带备份的算法,而且由于二叉树有方向,只能自顶向下,不能自底向上,说是动态规划,其实就是递归而已。。。。不过学了东西之后归类还是好的,而且在开始犯了一个2b的错误,为了简化代码下了如下错误的:
class Solution {
public:
int maxDepth(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
return depth(root);
}
int depth (TreeNode*root){
if(root == NULL){
return 0;
}
//2b的开始,导致depth左节点和右节点都计算了2次,直接导致超时,其实记下来就ok啦!
return ( depth(root->left) >depth(root->right)? depth(root->left) +1:depth(root->right)+1);
}
};
正确的:
class Solution {
public:
int maxDepth(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
return depth(root);
}
int depth (TreeNode*root){
if(root == NULL){
return 0;
}
int left = depth(root->left) ;
int right = depth(root->right);
return (left>right?left+1:right+1);
}
};