求二叉树的最大和最小深度-后序 前序 层序
给定二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明:叶子节点是指没有子节点的节点。
分析:后序求高度 前序求深度 层序的层数就是深度
#include "_myPrint.cpp"
#include "stack"
#include "queue"
using namespace std;
class Solution{
public:
int getDepth(TreeNode* root){
if (!root) return 0;
int leftDepth = getDepth(root -> left);
int rightDepth = getDepth(root -> right);
int nowDepth = max(leftDepth, rightDepth) + 1;
return nowDepth;
}
int getMinDepth(TreeNode* root){
if (!root) return 0;
int leftDepth = getMinDepth(root -> left);
int rightDepth = getMinDepth(root -> right);
if (root -> left && !root -> right) return leftDepth + 1;
if (root -> right && !root -> left) return rightDepth + 1;
return 1 + min(leftDepth, rightDepth);
}
int treeDepth(TreeNode* root){
int res = getMinDepth(root);
return res;
}
int res;
void getDepth_(TreeNode* root, int depth){
res = res > depth ? res : depth;
if (!root -> left && !root -> right) return;
if (root -> left) getDepth_(root -> left, depth + 1);
if (root -> right) getDepth_(root -> right, depth + 1);
return;
}
int maxdepth(TreeNode* root){
res = 0;
if (!root) return res;
getDepth_(root, 1);
return res;
}
int level_depth(TreeNode* root){
if (!root) 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* tmp = que.front();
que.pop();
if (tmp -> left) que.push(tmp -> left);
if (tmp -> right) que.push(tmp -> right);
}
}
return depth;
}
};
int main(){
Solution s;
TreeNode* root = new TreeNode(8);
TreeNode* l = new TreeNode(6);
TreeNode* r = new TreeNode(7);
root->left = l;
root->right = r;
int res = s.treeDepth(root);
cout << res << endl;
}
|