题目链接:
力扣(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 minDepth(TreeNode* root) {
- if(root == nullptr) return 0;
- std::queue
que; - que.push(root);
- int count = 0;
- while(!que.empty())
- {
- int size = que.size();
- count++;
- for(int i = 0; i < size; i++)
- {
- TreeNode* node = que.front();
- que.pop();
- if(node->left==nullptr && node->right==nullptr)
- {
- return count;
- }
- if(node->left) que.push(node->left);
- if(node->right) que.push(node->right);
- }
- }
- return count;
- }
- };
递归法:
三部曲:
1.int mdepth(Tnode* cur);
2.if(cur->left==null && cur->right==null) return 0;
3.int l = mdepth(cur->left);
int r = mdepth(cur->right);
return 1 + min(l, r);
自己写的错误代码:
- class Solution {
- public:
- int minDepth(TreeNode* root) {
- if(root == nullptr) return 0;
- return mdepth(root);
- }
-
- int mdepth(TreeNode* cur)
- {
- if(cur->left==nullptr && cur->right==nullptr) return 0;
- int l,r;
- if(cur->left) l = mdepth(cur->left);
- if(cur->right) r = mdepth(cur->right);
- return 1 + min(l,r);
- }
- };
正确代码:
- class Solution {
- public:
- int getDepth(TreeNode* node) {
- if (node == NULL) return 0;
- int leftDepth = getDepth(node->left); // 左
- int rightDepth = getDepth(node->right); // 右
- // 中
- // 当一个左子树为空,右不为空,这时并不是最低点
- if (node->left == NULL && node->right != NULL) {
- return 1 + rightDepth;
- }
- // 当一个右子树为空,左不为空,这时并不是最低点
- if (node->left != NULL && node->right == NULL) {
- return 1 + leftDepth;
- }
- int result = 1 + min(leftDepth, rightDepth);
- return result;
- }
-
- int minDepth(TreeNode* root) {
- return getDepth(root);
- }
- };
先序的递归更好理解:
- class Solution {
- private:
- int result;
- void getdepth(TreeNode* node, int depth) {
- // 函数递归终止条件
- if (root == nullptr) {
- return;
- }
- // 中,处理逻辑:判断是不是叶子结点
- if (root -> left == nullptr && root->right == nullptr) {
- res = min(res, depth);
- }
- if (node->left) { // 左
- getdepth(node->left, depth + 1);
- }
- if (node->right) { // 右
- getdepth(node->right, depth + 1);
- }
- return ;
- }
-
- public:
- int minDepth(TreeNode* root) {
- if (root == nullptr) {
- return 0;
- }
- result = INT_MAX;
- getdepth(root, 1);
- return result;
- }
- };