110.平衡二叉树
递归遍历
class Solution {
public:
int getHeight(TreeNode* node) {
if (node == nullptr) return 0;
int leftHeight = getHeight(node->left);
if (leftHeight == -1) return -1; //左子树如果是不平衡二叉树,向上传递-1
int rightHeight = getHeight(node->right);
if (rightHeight == -1) return -1; //右子树如果不是平衡二叉树,向上传递-1
return abs(rightHeight - leftHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);
//判断该节点左右子树高度差是否<=1,不是则返回-1,是则返回实际高度
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : 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 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 == 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 leftValue = sumOfLeftLeaves(root->left);
if (root->left != nullptr && root->left->left == nullptr &&
root->left->right == nullptr) {
leftValue = root->left->val;
}
int rightValue = sumOfLeftLeaves(root->right);
int sum = leftValue + rightValue;
return sum;
}
};
迭代法:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
stack<TreeNode*> st;
if (root == nullptr) return 0;
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;
}
};