给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
解题思路
递归+三元运算符
判断根节点是否存在,
不存在,返回0
存在,返回左子树、右子树最大的深度(递归),加1是表示加上“根节点”,并不是单指最初始的那个根节点,比如下面的 “3”,
每一个节点都可能是根节点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
return !root ? 0 : max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
```cpp []
/*
*递归三部曲:
*1.参数类型、返回类型
*2.递归终止条件
*3.递归单层逻辑
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr) return 0;
int left_depth = maxDepth(root->left);
int right_depth = maxDepth(root->right);
return 1 + max(left_depth, right_depth);
}
};
```
```cpp []
/**层次遍历:队列来做
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr) return 0;
queue<TreeNode*> que;
que.push(root);
int depth = 0;
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;
}
};
```
N叉树求深度:
```cpp []
/*N叉树递归求深度
// 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 == nullptr) return 0;
int depth = 0;
for(int i = 0; i<root->children.size(); i++){
depth = max(depth, maxDepth(root->children[i]));
}
return depth+1;
}
};
```
```cpp []
/*N叉树层次遍历求深度:队列,栈不行
// 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 == nullptr) return 0;
queue<Node*> que;
que.push(root);
int depth = 0;
while(!que.empty()){
int size = que.size();
depth++;
for(int i = 0; i<size; i++){
Node *node = que.front();
que.pop();
for(int j = 0; j<node->children.size(); j++){
if(node->children[j]) que.push(node->children[j]);
}
}
}
return depth;
}
};
```
忘记错误的思考方式,因为那确实太混乱。现在只需把能理解的东西建立在自己的大脑,学习别人的好的解法跟思维方式。