513 找树左下角的值
//递归
class Solution {
public:
int maxDepth = INT_MIN;
int result;
void traversal(TreeNode* root, int depth) {
if (root->left == NULL && root->right == NULL) {
if (depth > maxDepth) {
maxDepth = depth;
result = root->val;
}
return;
}
if (root->left) {
traversal(root->left, depth + 1);
}
if (root->right) {
traversal(root->right, depth + 1);
}
return;
}
int findBottomLeftValue(TreeNode* root) {
traversal(root, 1);
return result;
}
};
//迭代
class Solution {
public:
int findBottomLeftValue(TreeNode* root)
{
int res=0;
queue<TreeNode*>que;
que.push(root);
while(!que.empty())
{
int s=que.size();
for(int i=0;i<s;i++)
{
auto node=que.front();
que.pop();
if(i==0) res=node->val;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return res;
}
};
112路径总和
//宽搜
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum)
{
if(root==nullptr) return false;
queue<TreeNode*>que;
que.push(root);
queue<int>sum;
sum.push(root->val);
while(!que.empty())
{
int size=que.size();
for(int i=0;i<size;i++)
{
auto node=que.front();
que.pop();
auto temp=sum.front();
sum.pop();
if(!node->left&&!node->right&&temp==targetSum) return true;
if(node->left)
{
que.push(node->left);
sum.push(node->left->val+temp);
}
if(node->right)
{
que.push(node->right);
sum.push(node->right->val+temp);
}
}
}
return false;
}
};
//深搜
class Solution {
public:
int sum=0;
bool dfs(TreeNode* root, int targetSum)
{
sum+=root->val;
if(!root->left&&!root->right&&sum==targetSum) return true;
if(!root->left&&!root->right) return false;
if(root->left)
{
if(dfs(root->left,targetSum)) return true;
sum -= root->left->val;
}
if(root->right)
{
if(dfs(root->right,targetSum)) return true;
sum -= root->right->val;
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum)
{
if(root==nullptr) return false;
return dfs(root,targetSum);
}
};
105.从中序与前序遍历序列构造二叉树
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode* build(vector<int>& preorder,int preStart,int preEnd,vector<int>& inorder,int inStart,int inEnd)
{
if (preStart > preEnd) return NULL;
int rootVal=preorder[preStart];
int index=0;
for(int i=inStart;i<=inEnd;i++)
{
if(inorder[i]==rootVal)
{
index=i;
break;
}
}
TreeNode* root = new TreeNode(rootVal);
root->left = build(preorder, preStart+1, preStart+index-inStart,inorder, inStart, index-1);
root->right = build(preorder, preStart+index-inStart+1, preEnd,inorder, index+1, inEnd);
return root;
}
};