110. 平衡二叉树
1 /**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 * };
11 */
12 class Solution {
13 public:
14 bool isBalanced(TreeNode* root) {
15 return depth(root) != -1;
16 }
17 int depth(TreeNode* root){
18 if(root == nullptr) return 0;
19 int result = 0;
20 int left = depth(root->left);
21 if(left == -1) return -1;
22 int right = depth(root->right);
23 if(right == -1) return -1;
24 return abs(left - right) > 1 ? -1 : max(left,right) + 1;
25 }
26 };
257. 二叉树的所有路径
1 /**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 * };
11 */
12 class Solution {
13 public:
14 vector<string> binaryTreePaths(TreeNode* root) {
15 vector<string> result;
16 if(root->left == nullptr && root->right == nullptr)
17 result.push_back(to_string(root->val));
18 if(root->left != nullptr){
19 vector<string> left = binaryTreePaths(root->left);
20 for(int i = 0; i < left.size(); i++){
21 result.push_back(to_string(root->val) + "->" + left[i]);
22 }
23 }
24 if(root->right != nullptr){
25 vector<string> right = binaryTreePaths(root->right);
26 for(int i = 0; i < right.size(); i++){
27 result.push_back(to_string(root->val) + "->" + right[i]);
28 }
29 }
30 return result;
31 }
32 };
404. 左叶子之和
1 /**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 * };
11 */
12 class Solution {
13 public:
14 int sumOfLeftLeaves(TreeNode* root) {
15 if(root == nullptr) return 0;
16 int result = 0;
17 if(root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr)
18 result += root->left->val;
19 return result+ sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
20 }
21 };