leetcode 104. Maximum Depth of Binary Tree 111. Minimum Depth of Binary Tree
阿新 • • 發佈:2019-04-07
treenode right left leetcode oot tco binary 判斷 root
104:
class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL) return 0; int left = maxDepth(root->left); int right = maxDepth(root->right); return (left > right ? left : right) + 1; } };
111:
class Solution {public: int minDepth(TreeNode* root) { if(root == NULL) return 0; int left = minDepth(root->left); int right = minDepth(root->right); if(left == 0) return right + 1; else if(right == 0) return left + 1;else return left < right ? left + 1 : right + 1; } };
最小的深度這個題與最大的深度這個題稍稍有點不同,因為最小深度的計算必須從葉子節點開始,沒有葉子節點不能計算,所以1,2這種情況只能返回2,不能返回1。做個判斷即可。
leetcode 104. Maximum Depth of Binary Tree 111. Minimum Depth of Binary Tree