104. Maximum Depth of Binary Tree
Given the root
of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: 3
Example 2:
Input: root = [1,null,2] Output: 2
Constraints:
- The number of nodes in the tree is in the range
[0, 104]
. -100 <= Node.val <= 100
递归
后序:
class Solution {
public:
int getDepth(TreeNode*root){
if(root==NULL)return 0;
int leftDepth=getDepth(root->left);
int rightDepth=getDepth(root->right);
int maxD=1+max(leftDepth,rightDepth);
return maxD;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
思路:
根节点的高度是二叉树的最大高度,前序求的是深度,后序求的是高度。
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
使用后序遍历(左右中)
前序:
class Solution {
public:
int result;
void getDepth(TreeNode*root,int depth){
result=result>depth?result:depth;//middle
if(root->left==NULL && root->right==NULL)return;
if(root->left){//left
depth++;
getDepth(root->left,depth);
depth--;//回溯,--
}
if(root->right){//right
depth++;
getDepth(root->right,depth);
depth--;//回溯
}
return ;
}
int maxDepth(TreeNode* root) {
result=0;
if(root==NULL)return result;
getDepth(root,1);
return result;
}
};
思路:
深度回溯
迭代法
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL)return 0;
int depth=0;
queue<TreeNode*>que;
que.push(root);
while(!que.empty()){
depth++;
int size=que.size();
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;
}
};
559. Maximum Depth of N-ary Tree
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Example 1:
Input: root = [1,null,3,2,4,null,5,6] Output: 3
Example 2:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: 5
Constraints:
- The total number of nodes is in the range
[0, 104]
. - The depth of the n-ary tree is less than or equal to
1000
.
递归:
class Solution {
public:
int maxDepth(Node* root) {
if(root==NULL)return 0;
int depth=0;
for(int i=0;i<root->children.size();i++){
int l=maxDepth(root->children[i]);
depth=max(depth,l);
}
return depth+1;
}
};
迭代:
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++;
int size=que.size();
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;
}
};
注意:
这里的类型是Node*,不是TreeNode*,其次,注意children[j]里面不是i