题目链接:110. 平衡二叉树
题目描述:给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
代码实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getHeight(TreeNode* node) {
if (node == nullptr) {
return 0;
}
int left = getHeight(node->left);
if (left == -1) {
return -1;
}
int right = getHeight(node->right);
if (right == -1) {
return -1;
}
return abs(left-right) > 1 ? -1 : 1 + max(left, right);
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
};
题目链接:257. 二叉树的所有路径
题目描述:给你一个二叉树的根节点 root
,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
代码实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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);
}
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<int> path;
vector<string> result;
if(root == NULL) return result;
traversal(root, path, result);
return result;
}
};
题目链接:404. 左叶子之和
题目描述:给定二叉树的根节点 root
,返回所有左叶子之和。
代码实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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 && root->left->left == nullptr && root->left->right == nullptr) {
leftvalue = root->left->val;
}
int rightvalue = sumOfLeftLeaves(root->right);
int sum = leftvalue + rightvalue;
return sum;
}
};