513.找树左下角的值
class Solution {
int res=0;
int max_depth = 0;
void traversal(TreeNode* root, int depth)
{
if(!root->left&&!root->right)
{
if(depth>max_depth)
{
max_depth = depth;
res = root->val;
}
}
if(root->left) traversal(root->left,depth+1);
if(root->right) traversal(root->right, depth+1);
}
public:
int findBottomLeftValue(TreeNode* root) {
traversal(root, 1);
return res;
}
};
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) que.push(root);
int result = 0;
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 hasPathSum(TreeNode* root, int targetSum) {
if(root==NULL) return false;
targetSum -= root->val;
if(!root->left && !root->right)
{
if(targetSum==0) return true;
else return false;
}
if(root->left)
{
bool left = hasPathSum(root->left, targetSum);
if(left==true) return true;
}
if(root->right){
bool right = hasPathSum(root->right, targetSum);
if(right==true) return true;
}
return false;
}
};
113.路径总和ii
class Solution {
vector<vector<int>> res;
vector<int>path;
void traversal(TreeNode* root, int targetSum)
{
path.push_back(root->val);
targetSum -= root->val;
if(!root->left&&!root->right)
{
if(targetSum == 0) res.push_back(path);
}
if(root->left){
traversal(root->left, targetSum);
path.pop_back();
}
if(root->right)
{
traversal(root->right, targetSum);
path.pop_back();
}
return;
}
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(root==NULL) return res;
traversal(root, targetSum);
return res;
}
};
106.从中序与后序遍历序列构造二叉树
【文章讲解】
105.从前序与中序遍历序列构造二叉树
【文章讲解】