104.二叉树的最大深度 Maximun depth of Binary Tree
深度和高度求法都差不多,递归法的话用左右中遍历就可以了.
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL){
return 0;
}
int leftdepth = maxDepth(root->left);
int rightdepth = maxDepth(root->right);
return 1 + max(leftdepth, rightdepth);
}
};
111.二叉树的最小深度 Minimun Depth of Binary Tree
层序遍历
回顾一下层序遍历怎么写
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL){
return 0;
}
queue<TreeNode*> que;
que.push(root);
int size = 0;
int depth = 0;
while (!que.empty()){
size = que.size();
depth++;
while (size--){
TreeNode* node = que.front();
que.pop();
if (node->left) {
que.push(node->left);
}
if (node->right){
que.push(node->right);
}
if (!node->left && !node->right){
return depth;
}
}
}
return depth;
}
};
后序遍历
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 && root->right){
return 1 + rightdepth;
}
if (root->left && !root->right){
return 1 + leftdepth;
}
return 1 + min(leftdepth, rightdepth);
}
};
222.完全二叉树的节点个数 Count Complete Tree Nodes
写完很有感悟
普通递归法 时间复杂度O(N):
class Solution {
public:
int count(TreeNode* node){
if (node == NULL){
return 0;
}
int leftcount = count(node->left);
int rightcount = count(node->right);
int value = leftcount + rightcount + 1;
return value;
}
int countNodes(TreeNode* root) {
if (root == NULL){
return 0;
}
return count(root);
}
};
根据完全二叉树特性 时间复杂度O(log N):
class Solution {
public:
int count(TreeNode* node){
if (node == NULL) return 0;
TreeNode* left = node->left;
TreeNode* right = node->right;
int leftdepth = 0, rightdepth = 0;
while (left){
left = left->left;
leftdepth++;
}
while(right){
right=right->right;
rightdepth++;
}
if (leftdepth == rightdepth){
return (2 << leftdepth) - 1;
}
return count(node->left) + count(node->right) + 1;
}
int countNodes(TreeNode* root) {
if (root == NULL){
return 0;
}
return count(root);
}
};