Leetcode 104 二叉树的最大深度
一个节点的深度是指从根节点到该节点的层数,而高度是指从该节点到其子叶节点的层数。前序是求深度,后续是求高度。
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) {return 0;}
int leftdepth = maxDepth(root -> left);
int rightdepth = maxDepth(root -> right);
int depth = 1 + max(leftdepth, rightdepth);
return depth;
}
};
Leetcode 111 二叉树的最小深度
最小深度是指从根节点到它的叶子节点的最小值。
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 == NULL && root -> right != NULL) {return 1 + rightdepth;}
if(root -> left != NULL && root -> right == NULL) {return 1 + leftdepth;}
return 1 + min(leftdepth, rightdepth);
}
};
Leetcode 110 平衡二叉树
class Solution {
public:
int getHeight(TreeNode* node) {
if (node == NULL) {
return 0;
}
int leftHeight = getHeight(node->left);
if (leftHeight == -1) return -1;
int rightHeight = getHeight(node->right);
if (rightHeight == -1) return -1;
return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
Leetcode 257 二叉树的所有路径
要用到回溯。
class Solution {
public:
void getPath(TreeNode* node, vector<int> &path, vector<string> &result){
path.push_back(node -> val);
if(node -> left == NULL && node -> right == NULL){
int _size = path.size();
string s;
for(int i = 0; i < _size - 1; i++){
s += to_string(path[i]);
s += "->";
}
s += to_string(path[_size - 1]);
result.push_back(s);
return;
}
if(node -> left != NULL){
getPath(node -> left, path, result);
path.pop_back();
}
if(node -> right != NULL){
getPath(node -> right, path, result);
path.pop_back();
}
return;
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> result;
if(root == NULL) {return result;}
getPath(root, path, result);
return result;
}
};
Leetcode 404 左叶子节点之和
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL) {return 0;}
int leftVal = sumOfLeftLeaves(root -> left);
if(root -> left != NULL && root -> left ->left == NULL && root -> left -> right == NULL){
leftVal = root -> left -> val;
}
int rightVal = sumOfLeftLeaves(root -> right);
int sum = leftVal + rightVal;
return sum;
}
};
Leetcode 222 完全二叉树的节点数
按照普通的二叉树遍历
class Solution {
public:
int sum = 0;
void getNum(TreeNode* root){
if(root == NULL) {return;}
sum ++;
getNum(root -> left);
getNum(root -> right);
return;
}
int countNodes(TreeNode* root) {
getNum(root);
return sum;
}
};