提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
代码随想录算法训练营十七天|● 110.平衡二叉树 ● 257. 二叉树的所有路径 ● 404.左叶子之和
110.平衡二叉树判断
代码如下(示例):
递归法:
class Solution {
public:
// 返回以该节点为根节点的二叉树的高度,如果不是平衡二叉树了则返回-1
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;
}
};
递归求高度的同时递归判断高度差是否大于1。
257.二叉树的所有路径
代码如下(示例):
递归法:
class Solution {
vector<string> res;
string path;
public:
void travel(TreeNode* root,string path) {
path += to_string(root->val);
if(!root->left&&!root->right) {
res.push_back(path);
return;
}
path += "->";
if(root->left) travel(root->left,path);
if(root->right) travel(root->right,path);
}
vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return res;
travel(root, path);
return res;
}
};
总结就是多看多写,回溯法利用形参拷贝赋值就不用额外回溯
404.左子叶之和
递归法:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL) return 0;
if (root->left != NULL && root->left->left == NULL && root->left->right == NULL) {
int leftValue = root->left->val;
return leftValue + sumOfLeftLeaves(root->right);
}
return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
};
前序遍历迭代法:
class Solution {
int count = 0;
public:
void travel(TreeNode* root) {
if (root == NULL) return;
if (root->left != NULL && root->left->left == NULL && root->left->right == NULL) {
count += root->left->val;
}
travel(root->left);
travel(root->right);
}
int sumOfLeftLeaves(TreeNode* root) {
travel(root);
return count;
}
};
迭代法:
略