110.平衡二叉树
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:后序遍历求高度,高度判断是否平衡 | LeetCode:110.平衡二叉树_哔哩哔哩_bilibili
状态:未通过
解题思路:使用后序遍历的方法,求左右子树的高度差的绝对值,判断是否大于1 。如果大于1,说明不是平衡二叉树,否则就是平衡二叉树。
代码实现:
class Solution {
public:
int getHight(TreeNode* node){
if(node == NULL) return 0;
int leftHight = getHight(node->left);
if(leftHight == -1) return -1;
int rightHight = getHight(node->right);
if(rightHight == -1) return -1;
return abs(leftHight - rightHight) > 1 ? -1 : 1 + max(leftHight, rightHight);
}
bool isBalanced(TreeNode* root) {
if(getHight(root) == -1) return false;
return true;
}
};
257. 二叉树的所有路径
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:递归中带着回溯,你感受到了没?| LeetCode:257. 二叉树的所有路径_哔哩哔哩_bilibili
状态:未通过
递归法代码实现:
class Solution {
private:
void traversal(TreeNode* cur, vector<int>& path, vector<string>& result){
path.push_back(cur->val);
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;
}
};
迭代法代码实现:
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
stack<TreeNode*> treeSt;
stack<string> pathSt;
vector<string> result;
if(root == NULL) 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 == NULL && node->right == NULL){
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.左叶子之和
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:二叉树的题目中,总有一些规则让你找不到北 | LeetCode:404.左叶子之和_哔哩哔哩_bilibili
状态:通过
递归法代码实现:
class Solution {
private:
void traverser(TreeNode* node, int& sum){
if(node == NULL) return;
if(node->left != NULL && node->left->left == NULL && node->left->right == NULL){
sum += node->left->val;
}
traverser(node->left, sum);
traverser(node->right, sum);
}
public:
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
if(root == NULL) return 0;
traverser(root, sum);
return sum;
}
};
非递归法代码实现:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
stack<TreeNode*> st;
if (root == NULL) return 0;
st.push(root);
int result = 0;
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
if (node->left != NULL && node->left->left == NULL && node->left->right == NULL) {
result += node->left->val;
}
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
}
return result;
}
};