没错我就是伍声2009的粉丝,从今天起,模仿《从零单排》系列,菜鸡单刷LeetCode!
题目:
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.
解答:
树的深度优先遍历,求得树高度即可。然后需要用到递归的思想,假设子树的高度已知。最后,记得设定递归终点。
说归说,我这样的菜鸡还是会碰到问题……例如下面这个:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode *root) { if(root->left == NULL && root->right == NULL) { return 1; } if(root->left != NULL && root->right == NULL) { return (1+maxDepth(root->left)); } if(root->right != NULL && root->left == NULL) { return (1+maxDepth(root->right)); } else { return (1+maxDepth(root->right))>(1+maxDepth(root->left))?(1+maxDepth(root->right)):(1+maxDepth(root->left)); } } };
Runtime Error 了……原因是,当输入空树时无法处理。但是改了之后还是还有通过……原因是超时。想了半天,问题在这里:
return (1+maxDepth(root->right))>(1+maxDepth(root->left))?(1+maxDepth(root->right)):(1+maxDepth(root->left));
这样不就是把子树的 maxDepth 求解了四次么?正确方法应该将子树高度保存下来,这样只需要计算两次,节省一半时间。得到 AC:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode *root) { if(root == NULL) { return 0; } if(root->left == NULL && root->right == NULL) { return 1; } if(root->left != NULL && root->right == NULL) { return (1+maxDepth(root->left)); } if(root->right != NULL && root->left == NULL) { return (1+maxDepth(root->right)); } else { int l = maxDepth(root->left); int r = maxDepth(root->right); return (1+r)>(1+l)?(1+r):(1+l); } } };
时间: 2024-10-12 15:09:38