leetcode-华为专题-111. 二叉树的最小深度
// /** // * 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) { // int depth =INT_MAX; // if(root==NULL) // 节点为空,深度为0 // return 0; // if(root->left==NULL&&root->right==NULL) // 左右子树为空,深度为1 // return 1; // // 其他情况,分别对左右子树递归判断 // if(root->left) depth = min(minDepth(root->left), depth); // if(root->right) depth = min(minDepth(root->right), depth); // return depth+1; // //return min(minDepth(root->left), minDepth(root->right))+1; // } // }; /** * 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) { int depth = INT_MAX; if(root==NULL) return 0; if(root->left==NULL&&root->right==NULL) return 1; // 其实下面四句话有三层意思, // 如果左子树为空,则最后返回的depth+1,就是右子树的高度+1 // 如果右子树为空,则最后返回的depth+1,就是左子树的高度+1 // 如果两个数都不为空,则最后返回的depth+1,就是左子树与右子树高度的较小值+1. if(root->left) depth = min(depth,minDepth(root->left)); if(root->right) depth = min(depth, minDepth(root->right)); return depth+1; } };