代码随想录算法训练营第十七天
一、110.平衡二叉树
该题忽略了可以用-1来表示该节点已经不是平衡二叉树。用了两个递归,一个求高度,另一个判断平衡,复杂了很多。
class Solution {
public:
int getHeight(TreeNode* cur){
if(!cur) return 0;
int leftheight = getHeight(cur->left);
int rightheight = getHeight(cur->right);
int height = 1 + max(leftheight,rightheight);
return height;
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
int leftheight = getHeight(root->left);
int rightheight = getHeight(root->right);
if(abs(leftheight-rightheight) > 1) return false;
bool flag_left = isBalanced(root->left);
bool flag_right = isBalanced(root->right);
return flag_left && flag_right;
}
};
正确的解法:
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;
}
};
二、257.二叉树的所有路径
这道题目要求从根节点到叶子的路径,所以需要前序遍历,这样才方便让父节点指向孩子节点,找到对应的路径。在这道题目中涉及到回溯,因为我们要把路径记录下来,需要回溯来回退一个路径再进入另一个路径。
class Solution {
private:
void traversal(TreeNode* cur, string path, vector<string>& result) {
path += to_string(cur->val); // 中
if (cur->left == NULL && cur->right == NULL) {
result.push_back(path);
return;
}
if (cur->left){
traversal(cur->left, path + "->", result); // 左
}
if (cur->right){
traversal(cur->right, path + "->", result); // 右
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path;
if (root == NULL) return result;
traversal(root, path, result);
return result;
}
};
三、左叶子之和
判断当前节点是不是左叶子是无法判断的,必须要通过节点的父节点来判断其左孩子是不是左叶子。
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL) return 0;
if(root->left == NULL && root->right == NULL) 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;
}
};