找树左下角的值
力扣题目链接
class Solution {
public:
int maxDepth;
int res;
int findBottomLeftValue(TreeNode* root) {
maxDepth = 0;
if(root)
res = root->val;
getBottomLeftValue(root, 0);
return res;
}
void getBottomLeftValue(TreeNode* root, int depth){
if(!root)
return;
if(root->right)
getBottomLeftValue(root->right, depth+1);
// 最深
if(depth >= maxDepth){
maxDepth = depth;
res = root->val;
}
// 最左
if(root->left)
getBottomLeftValue(root->left, depth+1);
}
};
路径总和
题目链接
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(!root)
return false;
// 为叶子节点,且节点值为targetsum
if(!root->left && !root->right)
return root->val == targetSum;
bool leftPath = hasPathSum(root->left, targetSum - root->val);
bool rightPath = hasPathSum(root->right, targetSum - root->val);
return leftPath || rightPath;
}
};
路径总和II
题目链接
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
getPath(root, targetSum);
return res;
}
void getPath(TreeNode* root, int targetSum){
if(!root)
return;
// 叶子节点
if(!root->left && !root->right){
if(root->val == targetSum){
path.push_back(root->val);
res.push_back(path);
path.pop_back();
}
return;
}
//回溯
if(root->left){
path.push_back(root->val);
getPath(root->left, targetSum - root->val);
path.pop_back();
}
if(root->right){
path.push_back(root->val);
getPath(root->right, targetSum - root->val);
path.pop_back();
}
}
};
从中序与后序遍历序列构造二叉树
力扣题目链接
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int rootval = postorder[postorder.size()-1];
TreeNode* root = new TreeNode(rootval);
int l_size;
int r_size;
int index = 0;
while(index < inorder.size()){
if(inorder[index] == rootval){
l_size = index;
r_size = inorder.size() - index - 1;
break;
}
index++;
}
if(l_size > 0){
vector<int> in_left(inorder.begin(), inorder.begin() + l_size);
vector<int> post_left(postorder.begin(), postorder.begin() + l_size);
root->left = buildTree(in_left, post_left);
}
if(r_size > 0){
vector<int> in_right(inorder.begin() + index + 1, inorder.end());
vector<int> post_right(postorder.begin() + index, postorder.end() - 1);
root->right = buildTree(in_right, post_right);
}
return root;
}
};