LeetCode110. 平衡二叉树
题目链接
视频讲解
题解
class Solution {
public:
bool isBalanced(TreeNode* root) {
int height = getHeight(root);
if(height == -1) return false;
return true;
}
int getHeight(TreeNode* cur) {
if(!cur) return 0;
int leftheight = getHeight(cur -> left);
if(leftheight == -1) return -1;
int rightheight = getHeight(cur -> right);
if(rightheight == -1) return -1;
return abs(leftheight - rightheight) > 1 ? -1 : max(leftheight, rightheight) + 1;
}
};
LeetCode257. 二叉树的所有路径
题目链接
视频讲解
题解
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
vector<int> path;
if(!root) return res;
getTreePath(root, res, path);
return res;
}
void getTreePath(TreeNode* cur, vector<string>& res, vector<int>& path) {
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]);
res.push_back(sPath);
}
if(cur -> left) {
getTreePath(cur -> left, res, path);
path.pop_back();
}
if(cur -> right) {
getTreePath(cur -> right, res, path);
path.pop_back();
}
}
};
LeetCode404. 左叶子之和
题目链接
视频讲解
题解
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root) return 0;
if(root -> left == NULL && root -> right == NULL) return 0;
int leftCount = sumOfLeftLeaves(root -> left);
if(root -> left && !root -> left -> left && !root -> left -> right) {
leftCount = root -> left -> val;
}
int rightCount = sumOfLeftLeaves(root -> right);
return leftCount + rightCount;
}
};