【二叉树】计算二叉树深度【104. Maximum Depth of Binary Tree】【111. Minimum Depth of Binary Tree】

xiaoxiao2021-02-28  80

计算最大深度

题目链接: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; } };

转载请注明原文地址: https://www.6miu.com/read-94692.html

最新回复(0)