110.平衡二叉树
二叉树这里大部分题目都可以使用递归法
class Solution {
public:
int gethigh(TreeNode* root){
if (root == NULL){
return 0;
}
int lefthigh = gethigh(root->left);
if (lefthigh == -1) return -1;
int righthigh = gethigh(root->right);
if (righthigh == -1) return -1;
int ans;
if (abs(lefthigh-righthigh) > 1){
return -1;
} else {
ans = 1+max(lefthigh,righthigh);//以当前节点为根节点的树的最大高度
}
return ans;
}
bool isBalanced(TreeNode* root) {
return (gethigh(root) == -1)? false:true;
}
};
257. 二叉树的所有路径
使用栈来储存节点,然后进行递归。由于我们需要将栈当中的数据进行遍历输出,所以此处选择数组来模拟栈比较方便。
class Solution {
private:
void traversal(TreeNode* cur, vector<int>& path, vector<string>& result) {
path.push_back(cur->val); // 中,中为什么写在这里,因为最后一个节点也要加入到path中
// 这才到了叶子节点
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(); // 回溯
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if (root == NULL) return result;
traversal(root, path, result);
return result;
}
};
404.左叶子之和
先根据左叶子节点的定义来确认左节点,然后累加。
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL) return 0;
int leftsum = sumOfLeftLeaves(root->left);
if (root->left && !root->left->left && !root->left->right) {
leftsum = root->left->val;
}
int rightsum = sumOfLeftLeaves(root->right);
int sum = leftsum+rightsum;
return sum;
}
};