LeetCode 110平衡二叉树
题目链接:110.平衡二叉树
//自己写的递归
class Solution {
public:
int getDepth(TreeNode* node) {
if (node == nullptr) return 0;
return max(getDepth(node->left), getDepth(node->right)) + 1;
}
bool isBalanced(TreeNode* root) {
if (root == nullptr) return true;
return (isBalanced(root->left) && isBalanced(root->right) && abs(getDepth(root->left) - getDepth(root->right)) < 2);
}
};
//递归
class Solution {
public:
//既要考虑当前子树是否平衡,也要将高度作为参考值看更大的子树是否平衡
int getHeight(TreeNode* node) {
if (node == nullptr) return 0;
//如果当前传入节点为根节点的二叉树已经不是二叉平衡树了,还返回高度的话就没有意义了
//所以如果已经不是二叉平衡树了,直接返回-1来标记!
int leftHeight = getHeight(node->left);
if (leftHeight == -1) return -1;
int rightHeight = getHeight(node->right);
if (rightHeight == -1) return -1;
return abs(leftHeight - rightHeight) > 1 ? -1 : max(leftHeight, rightHeight) + 1;
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
};
LeetCode 257二叉树的所有路径
题目链接:257.二叉树的所有路径
//回溯
class Solution {
public:
vector<string> result;
string path;
void backtracking(TreeNode* node, string path) {//注意这里path不能是引用类型
path += to_string(node->val);
if (!node->left && !node->right) {
result.push_back(path);
return;
}
if (node->left) {
backtracking(node->left, path + "->");
}
if (node->right) {
backtracking(node->right, path + "->");
}
}
vector<string> binaryTreePaths(TreeNode* root) {
result.clear();
path.clear();
backtracking(root, path);
return result;
}
};
//迭代:前序遍历
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
stack<TreeNode*> treeSt;
stack<string> pathSt;
if (root == nullptr) return ans;
treeSt.push(root);
pathSt.push(to_string(root->val));
while (!treeSt.empty()) {
TreeNode* cur = treeSt.top(); treeSt.pop();
string path = pathSt.top(); pathSt.pop();
if (!cur->left && !cur->right) {
ans.push_back(path);
}
if (cur->right) {
treeSt.push(cur->right);
pathSt.push(path + "->" + to_string(cur->right->val));
}
if (cur->left) {
treeSt.push(cur->left);
pathSt.push(path + "->" + to_string(cur->left->val));
}
}
return ans;
}
};
LeetCode 404左叶子之和
题目链接:404.左叶子之和
//递归
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
if (root == nullptr) return sum;
sum += sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
if (root->left && !root->left->left && !root->left->right) sum += root->left->val;
return sum;
}
};
//迭代
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
if (root == nullptr) return sum;
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode* cur = st.top(); st.pop();
if (cur->left && !cur->left->left && !cur->left->right) sum += cur->left->val;
if (cur->right) st.push(cur->right);
if (cur->left) st.push(cur->left);
}
return sum;
}
};