又过了一道 LeetCode 上的通过数比较多的题(>= 40% 俗称 "水题"!!),顿时感到自己的基础不扎实,
但同时又感到庆幸,毕竟现在认识到自己的基础不扎实还不算晚(毕竟才大二...),好了,话不多说,直接看代码吧,
代码上面有解题步骤.
实现代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /** * 解题思路: * DFS 递归遍历 * 首先判断这棵树是空数的情况 * 同时也是递归的边界情况 * 首先求他的左子数的最大深度, * 然后求他的右子数的最大深度 * 比较求解! ** 注意: * 即使是root -> left == NULL * 或者 root -> right == NULL * 的情况,他的深度也不是0,毕竟他还有个根节点呢, * 所以一定要 maxDepth(root -> left)+1;(most importent!) **/ 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. if (!root) return 0; // 求左子数的最大深度 int lDepth = maxDepth(root -> left); // 求右子数的最大深度 int rDepth = maxDepth(root -> right); int max = lDepth > rDepth ? lDepth+1 : rDepth+1; return max; } };
转载于:https://blog.51cto.com/zhujifang/1380264