代码随想录算法训练营第十七天 | 110. 平衡二叉树、257. 二叉树的所有路径、404. 左叶子之和
110. 平衡二叉树
题目
解法
- 递归:后序遍历
class Solution {
public:
int getHeight(TreeNode* root) {
if(root == NULL) return 0;
int leftHeight = getHeight(root->left); // 左
if(leftHeight == -1) return -1;
int rightHeight = getHeight(root->right); // 右
if(rightHeight == -1) return -1;
return abs(rightHeight-leftHeight)>1 ? -1 : 1 + max(rightHeight, leftHeight); // 中
}
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<int> path;
vector<string> result;
if(root == nullptr) return result;
traversal(root, path, result);
return result;
}
};
404. 左叶子之和
题目
解法
class Solution {
public:
int leftNum(TreeNode* root) {
//终止条件
if(root == nullptr) return 0;
if(root->left == nullptr && root->right == nullptr) return 0;
// 单层递归逻辑
int num = 0;
if(root->left != nullptr && root->left->left == nullptr && root->left->right ==nullptr) {
num += root->left->val;
}
if(root->left) num += leftNum(root->left);// 左子树
if(root->right) num += leftNum(root->right);// 右子树
return num;
}
int sumOfLeftLeaves(TreeNode* root) {
return leftNum(root);
}
};
总结
递归三步:
1.确定递归函数参数和返回值;
2.确定终止条件
3.确定单层递归逻辑