104. Maximum Depth of Binary Tree
和111很像,只是递归的结构略有不同,可简单画图分析,求最大深度可以直接返回1+max(左子树深度,右子树深度),但是求最小深度时不可以,需要分别考虑左右子树为空的情况。可以举个反例子,比如,单斜树。
1 class Solution { 2 public: 3 int maxDepth(TreeNode* root) { 4 if (!root) return 0; 5 return 1 + max(maxDepth(root->left), maxDepth(root->right)); 6 } 7 };
111. Minimum Depth of Binary Tree
递归的典型应用,分清终止条件
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int minDepth(TreeNode *root) { 13 if (root == NULL) return 0; 14 if (root->left == NULL && root->right == NULL) return 1; 15 16 if (root->left == NULL) return minDepth(root->right) + 1; 17 else if (root->right == NULL) return minDepth(root->left) + 1; 18 else return 1 + min(minDepth(root->left), minDepth(root->right)); 19 } 20 21 };