题目链接:
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
我的思路:
递归法:
递归三部曲
我的代码:
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:int maxDepth(TreeNode* root) {int m = depth(root);return m;}int depth(TreeNode* cur){if(cur == nullptr) return 0;int left = depth(cur->left);int right = depth(cur->right);return 1 + max(left, right);}
};
层序遍历:
因为层序遍历我们是知道有多少层的,每一层count++就可以知道最大深度。
敲一下代码复习一遍层序遍历
class Solution {
public:int maxDepth(TreeNode* root) {if(root == nullptr) return 0;std:queue<TreeNode*> que;que.push(root);int count = 0;while(!que.empty()){int size = que.size();for(int i = 0; i < size; i++){TreeNode* tem = que.front();que.pop();if(tem->left) que.push(tem->left);if(tem->right) que.push(tem->right);}count++;}return count;}
};
先序遍历:
先序理解不了,看一下随想录思路
个人感觉还是递归的套路,只是返回值放到参数里,这个时候就要注意向左右传depth的值都只是+1过的
class solution {
public:int result;void getdepth(TreeNode* node, int depth) {result = depth > result ? depth : result; // 中if (node->left == NULL && node->right == NULL) return ;if (node->left) { // 左depth++; // 深度+1getdepth(node->left, depth);depth--; // 回溯,深度-1}if (node->right) { // 右depth++; // 深度+1getdepth(node->right, depth);depth--; // 回溯,深度-1}return ;}int maxDepth(TreeNode* root) {result = 0;if (root == NULL) return result;getdepth(root, 1);return result;}
};