110. 平衡二叉树
给定一个二叉树,判断它是否是 平衡二叉树。
题目链接:LeetCode110.平衡二叉树
文档讲解:代码随想录LeetCode110.平衡二叉树
题解
递归法
class Solution {
public:
int getHeight(TreeNode* node) {
if (node == nullptr)
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 : max(leftHeight, rightHeight) + 1;
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
};
257. 二叉树的所有路径
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
题解
回溯法
class Solution {
public:
void traversal(TreeNode* node, vector<int>& path, vector<string>& res) {
path.push_back(node->val);
if (!node->left && !node->right) {
string sPath;
for (int i = 0; i < path.size() - 1; i++) {
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]);
res.push_back(sPath);
return;
}
if (node->left) {
traversal(node->left, path, res);
path.pop_back();
}
if (node->right) {
traversal(node->right, path, res);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
vector<int> path;
if (!root)
return res;
traversal(root, path, res);
return res;
}
};
404. 左叶子之和
给定二叉树的根节点 root ,返回所有左叶子之和。
题目链接:LeetCode404.左叶子之和
文档讲解:代码随想录LeetCode404.左叶子之和
题解
递归法
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (!root)
return 0;
if (!root->left && !root->right)
return 0;
int leftSum = sumOfLeftLeaves(root->left);
if (root->left && !root->left->left && !root->left->right) {
leftSum = root->left->val;
}
int rightSum = sumOfLeftLeaves(root->right);
return leftSum + rightSum;
}
};
222. 完全二叉树的节点个数
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^h 个节点。
题目链接:LeetCode222.完全二叉树的节点个数
文档讲解:代码随想录LeetCode222.完全二叉树的节点个数
题解
利用完全二叉树的特征递归到某个深度一定会有左孩子或右孩子为满二叉树的特点
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root)
return 0;
TreeNode* left = root->left;
TreeNode* right = root->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 countNodes(root->left) + countNodes(root->right) + 1;
}
};