110.平衡二叉树
当左子树右子树高度差超过一时,即可判断该树不是平衡二叉树,用后序遍历将左右子树的高度返回给根结点,再由上层结点判断其左右子树高度差
class Solution {
public:
int getDepth(TreeNode*node){
if(node== nullptr)return 0;
int left= getDepth(node->left);//左
if(left==-1)return -1;
int right= getDepth(node->right);//右
if(right==-1)return -1;
int res;
if(abs(left-right)>1) res=-1;
else
res=1+ max(left,right);//中
return res;
}
bool isBalanced(TreeNode* root) {
int depth=getDepth(root);
if(depth==-1)return 0;
return 1;
}
};
257.二叉树的所有路径
在找到叶子后终止递归,回溯,并把找到的路径存到结果集中,遍历顺序为先序遍历,一刷仍不熟悉回溯,需要掌握中左右遍历顺序内部的代码实现
class Solution {
private:
void travel(TreeNode*node,vector<int> &path,vector<string> &res){
//中
path.push_back(node->val);
if(node->left== nullptr&&node->right== nullptr){
string sPath;
for (int i = 0; i < path.size() - 1; i++) {
// 将path里记录的路径转为string格式
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]); // 记录最后一个节点(叶子节点)
res.push_back(sPath); // 收集一个路径
return;
}
if(node->left){
travel(node->left,path,res);
path.pop_back();//回溯把最后一个结点弹出
}
if(node->right){
travel(node->right,path,res);
path.pop_back();
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> res;
if(root== nullptr)return res;
travel(root,path,res);
return res;
}
};
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;
}
};