110.平衡二叉树
要点:递归三部曲:1.确定递归函数的参数和返回值 2.确定终止条件 3.确定单次递归的处理逻辑。
这一题,单次递归处理就是判断左右子树高度的差值是否小于1。也是一道递归后序遍历求高度的题目。
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;
if (abs(leftHeight - rightHeight) > 1)
return -1;
return 1 + max(leftHeight, rightHeight);
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
};
257.二叉树的所有路径
要点:依然是递归,回溯理解起来有点费力,先放着
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& path, vector<string>& result) {
path.push_back(cur->val);
if (cur->left == nullptr && cur->right == nullptr) {
string sPath;
for (int i = 0; i < path.size() - 1; i++) {
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]);
result.push_back(sPath);
return;
}
if (cur->left) {
traversal(cur->left, path, result);
path.pop_back();
}
if (cur->right) {
traversal(cur->right, path, result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if (root == nullptr)
return result;
traversal(root, path, result);
return result;
}
};
404.左叶子之和
要点:什么叫左叶子的文字游戏,正常递归解法,单次递归处理略有不同
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr)
return 0;
if (root->left == nullptr && root->right == nullptr)
return 0;
int leftValue = sumOfLeftLeaves(root->left);
if (root->left && !root->left->left && !root->left->right) {
leftValue = root->left->val;
}
int rightValue = sumOfLeftLeaves(root->right);
int sum = leftValue + rightValue;
return sum;
}
};
222.完全二叉树的节点个数
要点:递归秒了,层序遍历也秒了
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr)
return 0;
int leftNum = countNodes(root->left);
int rightNum = countNodes(root->right);
int sum = leftNum + rightNum + 1;
return sum;
}
};