目录
12. LeetCode104. 二叉树的最大深度
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL){
return 0;
}
int depth=max(maxDepth(root->left),maxDepth(root->right))+1;
return depth;
}
};
13. LeetCode111. 二叉树的最小深度
注意:只有当遍历到叶子节点时,即左右子节点都为空,才能认为最小深度是1
要明白每个节点可能遇到的情况,从而分析得出相应的策略。
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL)return 0;
int leftDepth=minDepth(root->left);
int rightDepth=minDepth(root->right);
return root->left==NULL||root->right==NULL?
leftDepth+rightDepth+1:min(leftDepth,rightDepth)+1;
}
};
class Solution {
class Info{
public:
int minDepth;
Info(int minDepth){
this->minDepth=minDepth;
}
};
public:
int minDepth(TreeNode* root) {
Info data=process(root);
return data.minDepth;
}
Info process(TreeNode*node){
if(node==NULL)return Info(0);
if(node->left==NULL&&node->right==NULL)return Info(1);
Info leftData=process(node->left);//向左子树要信息
Info rightData=process(node->right);//向右子树要信息
/*
处理当前信息,分析当前节点左右子树情况
1.左右子节点都为空,说明是叶子节点,0+0+1=1
2.左右子节点有一个为空,那就是不为空的子树高度+1,其中空的深度是0,不影响
3.都不为空,左右最小高度+1
*/
if(node->left==NULL||node->right==NULL)
return Info(leftData.minDepth+rightData.minDepth+1);
return Info(min(leftData.minDepth,rightData.minDepth)+1);
}
};
以上是求二叉树深度的递归代码,如果想要迭代求二叉树深度,那只要利用另一个容器(队列/栈)层序遍历二叉树。
对于最大深度:只要容器里还有节点,就继续迭代。
对于最小深度:只要容器里有某个节点无左右子节点,就停止迭代。