题意:输出一个二叉树的最小深度。
思路:搜索一下就行了。
注意:搜索的时候,是比较每个子树的左右子树的大小,每个子树的深度要加上根节点!
class Solution { public: int run(TreeNode *root) { if (root == NULL) return 0; //空树 if (root->left == NULL) return run(root->right) + 1; if (root->right == NULL) return run(root->left) + 1; int left = run(root->left); int right = run(root->right); return (left < right) ? (left+1) : (right+1); } };
兄弟题
maximum-depth-of-binary-tree
题意:输出最大的二叉树的深度
class Solution { public: int maxDepth(TreeNode *root) { if (root == NULL)return 0; if (root->left == NULL) maxDepth(root->right) + 1; if (root->right == NULL)maxDepth(root->left) + 1; int left = maxDepth(root->left) + 1; int right = maxDepth(root->right) + 1; return left > right ? left : right; } };