513.找树左下角的值
//迭代法
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*>que;
if(root == nullptr) return 0;
int result = 0;
que.push(root);
while(!que.empty()){
int size = que.size();
for(int i=0;i<size;i++){
TreeNode* node = que.front();
que.pop();
if(i == 0) result = node->val;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return result;
}
};
112. 路径总和
class Solution {
public:
bool traversal(TreeNode* cur,int count){
if(!cur->left && !cur->right && count==0) return true;
if(!cur->left && !cur->right) return false;
if(cur->left){
if(traversal(cur->left,count-cur->left->val)) return true;
}
if(cur->right){
if(traversal(cur->right,count-cur->right->val)) return true;
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return false;
return traversal(root,targetSum - root->val);
}
};
//113
class Solution {
public:
vector<vector<int>>result;
vector<int>path;
// 递归函数不需要返回值,因为要遍历整个树
void traversal(TreeNode* cur, int count){
if(!cur->left && !cur->right && count==0){
result.push_back(path);
return ;
}
if(!cur->left && !cur->right) return ;
if(cur->left){
path.push_back(cur->left->val);
traversal(cur->left,count-cur->left->val);
path.pop_back();
}
if(cur->right){
path.push_back(cur->right->val);
traversal(cur->right,count-cur->right->val);
path.pop_back();
}
return ;
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return result;
path.push_back(root->val);
traversal(root,targetSum-root->val);
return result;
}
};
106.从中序与后序遍历序列构造二叉树
class Solution {
public:
TreeNode* traversal(vector<int>& inorder, vector<int>& postorder){
if(postorder.size() == 0) return nullptr;
//后序最后一个数值即为根节点值
int rootVal = postorder[postorder.size()-1];
TreeNode* root = new TreeNode(rootVal);
//叶子结点
if(postorder.size() == 1) return root;
//找到中序分割点下标
int index;
for(index=0;index < inorder.size();index++){
if(rootVal == inorder[index]) break;
}
//切割中序数组
vector<int>leftInorder(inorder.begin(),inorder.begin()+index);
vector<int>rightInorder(inorder.begin()+index+1,inorder.end());
//舍弃末尾数值
postorder.resize(postorder.size()-1);
//切割后序数组
vector<int>leftPostorder(postorder.begin(),postorder.begin()+leftInorder.size());
vector<int>rightPostorder(postorder.begin()+leftInorder.size(),postorder.end());
//构建二叉树
root->left = traversal(leftInorder,leftPostorder);
root->right = traversal(rightInorder,rightPostorder);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(inorder.size()==0 ||postorder.size()==0) return nullptr;
return traversal(inorder,postorder);
}
};