计算最大深度
题目链接:https://leetcode.com/problems/maximum-depth-of-binary-tree/#/description
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int cnt=0; int maxDepth(TreeNode* root) { if(root==NULL) return 0; return max(maxDepth(root->left)+1,maxDepth(root->right)+1); } };计算最小深度minDepth
最小深度是从根节点到最近叶节点的最短路径上的节点数。
题目链接:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int minDepth(TreeNode* root) { if(root==NULL) return 0; if(root->left==NULL&&root->right==NULL) return 1; if(root->left==NULL) return minDepth(root->right)+1; if(root->right==NULL) return minDepth(root->left)+1; return min(minDepth(root->left),minDepth(root->right))+1; } };