目录
[222. 完全二叉树的节点个数](#222. 完全二叉树的节点个数)
[110. 平衡二叉树](#110. 平衡二叉树)
[257. 二叉树的所有路径](#257. 二叉树的所有路径)
[404. 左叶子之和](#404. 左叶子之和)
222. 完全二叉树的节点个数
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root)return 0;
return countNodes(root->left)+countNodes(root->right)+1;
}
};
110. 平衡二叉树
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int getHeight(TreeNode* node){
if(!node)return 0;
int leftHeight=getHeight(node->left);
if(leftHeight==-1)return -1;
int rightHeight=getHeight(node->right);
if(rightHeight==-1)return -1;
if(abs(leftHeight-rightHeight)>1)return -1;
else return 1+max(leftHeight,rightHeight);
}
public:
bool isBalanced(TreeNode* root) {
if(getHeight(root)==-1)return false;
else return true;
}
};
257. 二叉树的所有路径
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
void dfs(TreeNode* cur, string path, vector<string>& result) {
path += to_string(cur->val);
if (!cur->left&&!cur->right) {
result.push_back(path);
return;
}
if (cur->left)dfs(cur->left, path + "->", result);
if (cur->right)dfs(cur->right, path + "->", result);
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path;
if (!root) return result;
dfs(root, path, result);
return result;
}
};
404. 左叶子之和
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (!root) return 0;
int sum = sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
TreeNode* left = root->left;
if (left && !left->left&& !left->right) sum += left->val;
return sum;
}
};
