-
110.平衡二叉树
-
class Solution { public: int sheng(TreeNode* a) { queue<TreeNode*> b; int ret = 1; if (a != NULL) b.push(a); while (!b.empty()) { int size = b.size(); for (int i = 0; i < size; i++) { TreeNode* cur = b.front(); b.pop(); if (cur->left) b.push(cur->left); if (cur->right) b.push(cur->right); } ret++; } return ret; } bool isBalanced(TreeNode* root) { int s1=1,s2=1; if (root == NULL ) return true; if (root->left) s1 = sheng(root->left); if (root->right) s2 = sheng(root->right); return abs(s1 - s2) <=1; } };
-
257. 二叉树的所有路径
-
class Solution { public: vector<string> ret; vector<int>ans; void dfs(TreeNode* a) { ans.push_back(a->val); if (a->left == NULL && a->right == NULL) { string k; for (int i = 0; i < ans.size() - 1; i++) { k += to_string(ans[i]); k = k + "->"; } k+=to_string(ans[ans.size()-1]); ret.push_back(k); return; } if (a->left) { dfs(a->left); ans.pop_back(); } if (a->right) { dfs(a->right); ans.pop_back(); } } vector<string> binaryTreePaths(TreeNode* root) { dfs(root); return ret; } };
-
404.左叶子之和
-
class Solution { public: int ret = 0; void seek_left(TreeNode* node) { if (node == NULL) return; if (node->left) { if (node->left->left == NULL && node->left->right == NULL) { ret = ret + node->left->val; } } if (node->left) { seek_left(node->left); } if (node->right) { seek_left(node->right); } return; } int sumOfLeftLeaves(TreeNode* root) { seek_left(root); return ret; } };