目录
513 找树左下角的值
用层序遍历来做比较简单
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
map<int, int> m;
int cnt = 0;
int sum = 0;
int pos = 0;
que.push(root);
while(!que.empty()){
sum = que.size();
pos = sum;
while(sum--){
TreeNode* node = que.front();
que.pop();
m[cnt++] = node->val;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return m[cnt-pos];
}
};
112 路径总和
class Solution {
public:
bool isRoadSum(TreeNode* node, int targetSum, vector<int> &vals){
// if(node == NULL) return false;
vals.push_back(node->val);//中
if(node->left == NULL && node->right == NULL){
int sum = 0;
for(int i = 0; i < vals.size(); i++){
sum += vals[i];
}
if(targetSum == sum){
return true;
}
}
bool leftB = false;
if(node->left){//左
leftB = isRoadSum(node->left, targetSum, vals);
if(leftB == false){
vals.pop_back();
}
}
bool rightB = false;
if(node->right){//左
rightB = isRoadSum(node->right, targetSum, vals);
if(rightB == false){
vals.pop_back();
}
}
return leftB || rightB;
}
bool hasPathSum(TreeNode* root, int targetSum) {
vector<int> vals;
if(root == NULL) return false;
return isRoadSum(root, targetSum, vals);
}
};
106 从中序与后序遍历序列构造二叉树
class Solution {
public:
TreeNode* t(vector<int> &inorder, vector<int> &postorder){
if(postorder.size() == 0) return NULL;
int rootval = postorder[postorder.size() - 1];
TreeNode* root = new TreeNode(rootval);
if(postorder.size() == 1) return root;
int midIndex;
for(midIndex = 0; midIndex < inorder.size(); midIndex++){
if(inorder[midIndex] == rootval){
break;
}
}
vector<int> inorderLeft(inorder.begin(), inorder.begin() + midIndex);
vector<int> inorderRight(inorder.begin() + midIndex + 1, inorder.end());
postorder.resize(postorder.size() - 1);
vector<int> postorderLeft(postorder.begin(), postorder.begin() + inorderLeft.size());
vector<int> postorderRight(postorder.begin() + inorderLeft.size(), postorder.end());
root->left = t(inorderLeft, postorderLeft);//左
root->right = t(inorderRight, postorderRight);//右
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(inorder.size() == 0 || postorder.size() == 0){
return NULL;
}
return t(inorder, postorder);
}
};