110.平衡二叉树
class Solution {
public:
int getheight(TreeNode* node) {
if (node == nullptr) return 0;
int leftheight = getheight(node->left);
if (leftheight == -1) return -1;
int rightheight = getheight(node->right);
if (rightheight == -1) return -1;
if (abs(rightheight - leftheight) > 1) return -1;
else return 1 + max(leftheight, rightheight);
}
bool isBalanced(TreeNode* root) {
int result = getheight(root);
if (result == -1) return false;
return 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 s;
for (int i = 0; i < path.size() - 1; i++) {
s += to_string(path[i]);
s += "->";
}
s += to_string(path[path.size() - 1]);
result.push_back(s);
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 == nullptr) return result;
traversal(root, path, result);
return result;
}
};
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
stack<TreeNode*> treeSt;
stack<string> pathSt;
vector<string> result;
if (root == nullptr) return result;
treeSt.push(root);
pathSt.push(to_string(root->val));
while (!treeSt.empty()) {
TreeNode* node = treeSt.top();
treeSt.pop();
string path = pathSt.top();
pathSt.pop();
if (node->left == nullptr && node->right == nullptr) result.push_back(path);
if (node->right) {
treeSt.push(node->right);
pathSt.push(path + "->" + to_string(node->right->val));
}
if (node->left) {
treeSt.push(node->left);
pathSt.push(path + "->" + to_string(node->left->val));
}
}
return result;
}
};
404.左叶子之和
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) return 0;
if (root->left == nullptr && root->right == nullptr) return 0;
int leftnum = sumOfLeftLeaves(root->left);
if (root->left && !root->left->left && !root->left->right) leftnum = root->left->val;
int rightnum = sumOfLeftLeaves(root->right);
return leftnum + rightnum;
}
};
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
stack<TreeNode*> st;
if (root != nullptr) st.push(root);
int result = 0;
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
if (node->left != nullptr && node->left->left == nullptr && node->left->right == nullptr) result += node->left->val;
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
}
return result;
}
};