110.平衡二叉树
class Solution {
public:
int getDepth(TreeNode* node){
if(!node) return 0;
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
if(leftDepth == -1 || rightDepth == -1)
return -1;
int depthDiff = abs(leftDepth - rightDepth);
if(depthDiff > 1)
return -1;
else
return 1 + max(leftDepth, rightDepth);
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
int result = getDepth(root);
return result == -1 ? false : true;
}
};
257. 二叉树的所有路径
class Solution {
public:
void traverse(TreeNode* node, vector<int>& path, vector<string>& result){
path.push_back(node->val);
if(node->left == nullptr && node->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(node->left){
traverse(node->left, path, result);
path.pop_back();
}
if(node->right){
traverse(node->right, path, result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if(!root) return result;
traverse(root, path, result);
return result;
}
};
404.左叶子之和
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;
}
};