day15_keep going on
110. 平衡二叉树 - 力扣(LeetCode)
class Solution {int dfs(TreeNode* node){if(node == nullptr) return 0;int l = dfs(node->left);int r = dfs(node->right);return max(l , r) + 1;}
public:bool isBalanced(TreeNode* root) {if(root == nullptr) return true;int l = dfs(root->left);int r = dfs(root->right);return abs( l - r ) < 2 && isBalanced(root->left) && isBalanced(root->right);}
};
257. 二叉树的所有路径 - 力扣(LeetCode)
class Solution {
private:void dfs(vector<string> & res, string path, TreeNode* node){path += to_string(node->val);if(node->left == nullptr && node->right == nullptr){res.push_back(path);return;}path += "->";if(node->left) dfs(res, path, node->left);if(node->right) dfs(res, path, node->right);}
public:vector<string> binaryTreePaths(TreeNode* root) {vector<string> res;if(root == nullptr) return res;dfs(res, "", root);return res;}
};
404. 左叶子之和 - 力扣(LeetCode)
class Solution {
public:int sumOfLeftLeaves(TreeNode* root) {if(root == nullptr) return 0;int sum = 0;// 判断是不是左叶子节点if(root->left && root->left->left == nullptr && root->left->right == nullptr){sum += root->left->val;}else{sum += sumOfLeftLeaves(root->left);}sum += sumOfLeftLeaves(root->right);return sum;}
};
222. 完全二叉树的节点个数 - 力扣(LeetCode)
class Solution {
public:int countNodes(TreeNode* root) {if(root == nullptr) return 0;// 分别计算左右子树的高度TreeNode* left = root->left;TreeNode* right = root->right;int hl = 0, hr = 0;while(left){hl++;left = left->left;}while(right){hr++;right = right->right;}if(hl == hr){return (2 << hl) - 1; // 比如 2 << 1 == 2^2 向左移位}return countNodes(root->left) + countNodes(root->right) + 1;}
};