110.平衡二叉树
复习一下递归三部曲:
1.确定递归函数的参数和返回值
2.确认终止条件
3.确认单层递归的逻辑
此题为比较高度,使用左右中后序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(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;
int result;
if(abs(rightheight-leftheight)>1)result=-1;
else{
result=1+max(leftheight,rightheight);
}
return result;
}
bool isBalanced(TreeNode* root) {
return getheight(root)==-1?false:true;
}
};
257. 二叉树的所有路径
回溯和递归是相辅相成的,只要有递归就一定有回溯
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void traversal(TreeNode* cur,vector<int>& path,vector<string>& result){
path.push_back(cur->val);
if(cur->left == NULL&&cur->right==NULL){
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==NULL)return result;
traversal(root,path,result);
return result;
}
};
404.左叶子之和
1.确定递归函数的参数和返回值
判断一个树的左叶子节点之和,那么一定要传入树的根节点,递归函数的返回值为数值之和,所以为int
2.确定终止条件
如果遍历到空节点,那么左叶子值一定是0
3.确定单层递归的逻辑
当遇到左叶子节点的时候,记录数值,然后通过递归求取左子树左叶子之和,和右子树左叶子之和,相加便是整个树的左叶子之和。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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;
}
};