文章目录
1. 二叉树的最大深度
解析
Leetcode104 二叉树的最大深度
(2)思路
先序遍历 + 递归思路
(3)代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
int leftdepth = maxDepth(root->left) + 1;
int rightdepth = maxDepth(root->right) + 1;
return leftdepth > rightdepth ? leftdepth : rightdepth;
}
};
(4)总结
无
2. 二叉树的最小深度
(1)解析
Leetcode226 二叉树的翻转
(2)思路
二叉树的左右子树为空时的判断
(3)代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
int leftdepth = minDepth(root->left);
int rightdepth = minDepth(root->right);
if(root->left == NULL && root->right != NULL)
return rightdepth + 1;
else if(root->left != NULL && root->right == NULL)
return leftdepth + 1;
else
return 1 + (leftdepth > rightdepth ? rightdepth : leftdepth);
}
};
(4)总结
无
3. 完全二叉树的节点个数
Leetcode222 完全二叉树的节点个数
(2)思路
左子树+右子树+中间节点
(3)代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL)
return 0;
int left = countNodes(root->left);
int right = countNodes(root->right);
return left + right + 1;
}
};
(4)总结
无
4. n叉树的最大深度
Leetcode222 完全二叉树的节点个数
(2)思路
1.分层迭代遍历
2.递归遍历
(3)代码
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
//迭代遍历
class Solution {
public:
int maxDepth(Node* root) {
if(root == NULL)
return 0;
int depth = 0;
queue<Node*> que;
que.push(root);
while(!que.empty())
{
depth += 1;
int size = que.size();
for(int i = 0; i < size; ++i)
{
Node *tmp = que.front();
for(int j = 0; j < tmp->children.size(); ++j)
que.push(tmp->children[j]);
que.pop();
}
}
return depth;
}
};
//递归遍历
class Solution {
public:
int maxDepth(Node* root) {
if(root == NULL)
return 0;
int depth = 0;
for(int i = 0; i < root->children.size(); ++i)
{
depth = max(depth, maxDepth(root->children[i]));
}
return depth + 1;
}
};