110.平衡二叉树
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
使用动态规划,刚开始设置动态规划出来的。
接着求左右节点的高度,当然在求完左右节点之后要确认是否是-1,如果是-1就直接返回了,
如果不是-1就作差值,高度差>1就返回-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 GetBool(TreeNode* Cur) {if (Cur == nullptr) return 0;int left = GetBool(Cur->left); if (left == -1) return -1;int right = GetBool(Cur->right);if (right == -1) return -1;if (abs(left - right) > 1) return -1;else return 1 + max(left, right);}bool isBalanced(TreeNode* root) {return GetBool(root) == -1 ? false : true;}
};
257. 二叉树的所有路径
题目链接:257. 二叉树的所有路径 - 力扣(LeetCode)
/*** 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:void traveral (TreeNode* Cur, vector<int>& Path, vector<string>& Result) {Path.push_back(Cur->val);if (Cur->left == nullptr && Cur->right == nullptr) {string String;for (int i = 0; i < Path.size() -1; i++) {String += to_string(Path[i]);String += "->";}String += to_string(Path[Path.size() - 1]);Result.push_back(String);return;}if (Cur->left) {traveral(Cur->left,Path, Result);Path.pop_back();}if (Cur->right) {traveral(Cur->right,Path, Result);Path.pop_back();}}vector<string> binaryTreePaths(TreeNode* root) {vector<int> Path;vector<string> Result;if (root == nullptr) return Result;traveral(root, Path, Result);return Result;}
};
404.左叶子之和
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
/*** 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 == NULL) return 0;if (root->left == NULL && root->right== NULL) return 0;int leftValue = sumOfLeftLeaves(root->left); // 左if (root->left && !root->left->left && !root->left->right) { // 左子树就是一个左叶子的情况leftValue = root->left->val;}int rightValue = sumOfLeftLeaves(root->right); // 右int sum = leftValue + rightValue; // 中return sum;}
};