classSolution{public:boolisBalanced(TreeNode* root){if(!root)returntrue;int left =isHigh(root->left);int right =isHigh(root->right);if(abs(left - right)>1)returnfalse;returnisBalanced(root->left)&&isBalanced(root->right);}intisHigh(TreeNode* root){if(!root)return0;returnmax(isHigh(root->left),isHigh(root->right))+1;}};
257. 二叉树的所有路径
代码
classSolution{public:
vector<string> res;
vector<int> path;
vector<string>binaryTreePaths(TreeNode* root){if(!root)return res;traversal(root);return res;}voidtraversal(TreeNode* root){
path.push_back(root->val);if(root->left ==nullptr&& root->right ==nullptr){
string s ="";for(int i =0; i < path.size()-1;i ++){
s +=to_string(path[i]);
s +="->";}
s +=to_string(path[path.size()-1]);
res.push_back(s);return;}if(root->left){traversal(root->left);
path.pop_back();}if(root->right){traversal(root->right);
path.pop_back();}}};
404. 左叶子之和
代码
classSolution{public:int res =0;intsumOfLeftLeaves(TreeNode* root){if(!root)return0;if(root->left && root->left->left ==nullptr&& root->left->right ==nullptr){
res += root->left->val;}sumOfLeftLeaves(root->left);sumOfLeftLeaves(root->right);return res;}};
513. 找树左下角的值
代码
classSolution{public:intfindBottomLeftValue(TreeNode* root){if(!root)return0;
queue<TreeNode*> q;int res;
q.push(root);while(!q.empty()){int size = q.size();
res = q.front()->val;for(int i =0; i < size; i ++){auto a = q.front();
q.pop();if(a->left) q.push(a->left);if(a->right) q.push(a->right);}}return res;}};
classSolution{public:
unordered_map<int,int> map;
TreeNode*buildTree(vector<int>& inorder, vector<int>& postorder){int n = inorder.size();for(int i =0; i < n; i ++){
map[inorder[i]]= i;}returndfs(inorder, postorder,0, n -1,0, n -1);}
TreeNode*dfs(vector<int>& inorder, vector<int>& postorder,int il,int ir,int pl,int pr){if(pl > pr)returnnullptr;int k = map[postorder[pr]]- il;
TreeNode* root =newTreeNode(postorder[pr]);
root->left =dfs(inorder, postorder, il, il + k -1, pl, pl + k -1);
root->right =dfs(inorder, postorder, il + k +1, ir, pl + k, pr -1);return root;}};
105. 从前序与中序遍历序列构造二叉树
代码
classSolution{public:
unordered_map<int,int> pos;
TreeNode*buildTree(vector<int>& preorder, vector<int>& inorder){int n = inorder.size();for(int i =0; i < n; i ++){
pos[inorder[i]]= i;}returndfs(preorder, inorder,0, n -1,0, n -1);}
TreeNode*dfs(vector<int>& pre, vector<int>& ino,int pl,int pr,int ll,int lr){if(pl > pr)returnNULL;int k = pos[pre[pl]]- ll;
TreeNode* root =newTreeNode(pre[pl]);
root->left =dfs(pre, ino, pl +1, pl + k, ll, ll + k -1);
root->right =dfs(pre, ino, pl + k +1, pr, ll + k +1, lr);return root;}};