递归:
class Solution {
public:
int max = 0;
int result = 0;
void traversal(TreeNode* root, int depth) {
if(root->left == NULL && root->right == NULL) {
if(depth > max) {
max = depth;
result = root->val;
return;
}
}
if(root->left != NULL) {
traversal(root->left, depth + 1);
}
if(root->right != NULL) {
traversal(root->right, depth + 1);
}
}
int findBottomLeftValue(TreeNode* root) {
if(root == NULL) return 0;
traversal(root, 1);
return result;
}
};
层序遍历:
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
if(root == NULL) return 0;
queue<TreeNode*> que;
que.push(root);
int result = 0;
while(!que.empty()) {
int size = que.size();
for(int i = 0; i < size; i++) {
TreeNode* tem = que.front();
que.pop();
if(tem->right != NULL) que.push(tem->right);
if(tem->left != NULL) que.push(tem->left);
if(i == size - 1) {
result = tem->val;
}
}
}
return result;
}
};
递归法:
class Solution {
public:
bool judge = false;
void traversal(TreeNode* root, int path, int targetSum) {
if(root->left == NULL && root->right == NULL) {
path += root->val;
if(path == targetSum) {
judge = true;
}
return;
}
if(root->left != NULL) {
traversal(root->left, path + root->val, targetSum);
}
if(root->right != NULL) {
traversal(root->right, path + root->val, targetSum);
}
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == NULL) return judge;
traversal(root, 0, targetSum);
return judge;
}
};
递归法:
class Solution {
public:
vector<vector<int>> result;
int target = 0;
void traversal(TreeNode* root, vector<int> path, int pathSum) {
if(root->left == NULL && root->right == NULL) {
if(pathSum == target) {
result.push_back(path);
}
return;
}
if(root->left != NULL) {
path.push_back(root->left->val);
traversal(root->left, path, pathSum + root->left->val);
path.pop_back();
}
if(root->right != NULL) {
path.push_back(root->right->val);
traversal(root->right, path, pathSum + root->right->val);
path.pop_back();
}
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(root == NULL) return result;
vector<int> path;
path.push_back(root->val);
target = targetSum;
traversal(root, path, root->val);
return result;
}
};