二叉树的深度
- 二叉树的深度为:根节点到叶子节点的路径上的节点数。
层序遍历-求最大深度
class Solution {public: int maxDepth(TreeNode* root) { if (root == NULL) return 0; int depth = 0; queue<TreeNode*> que; que.push(root); while(!que.empty()) { int size = que.size(); depth++; // 记录深度 for (int i = 0; i < size; i++) { TreeNode* node = que.front(); que.pop(); if (node->left) que.push(node->left); if (node->right) que.push(node->right); } } return depth; }};
层序遍历-求最小深度
class Solution {public: int minDepth(TreeNode* root) { if (root == NULL) return 0; int depth = 0; queue<TreeNode*> que; que.push(root); while(!que.empty()) { int size = que.size(); depth++; // 记录最小深度 for (int i = 0; i < size; i++) { TreeNode* node = que.front(); que.pop(); if (node->left) que.push(node->left); if (node->right) que.push(node->right); // 当左右孩子都为空的时候,说明是最低点的一层了,退出 if (!node->left && !node->right) { return depth; } } } return depth; }};
递归写法-求最小深度
class Solution {public: int minDepth(TreeNode* root) { if (root == NULL) return 0; if (root->left == NULL && root->right != NULL) { return 1 + minDepth(root->right); } if (root->left != NULL && root->right == NULL) { return 1 + minDepth(root->left); } return 1 + min(minDepth(root->left), minDepth(root->right)); }};