- 513.找树左下角的值
- 112. 路径总和 113.路径总和ii
- 106.从中序与后序遍历序列构造二叉树 105.从前序与中序遍历序列构造二叉树
513.找树左下角的值:逐步增加深度,当在最后一层深度 第一次就会获取到最左侧的
class Solution {
public: // 深度最大的第一个,遍历都行
// 遍历三部曲:
// 1先找到递归函数返回值和参数
int result;
int maxdepth = INT_MIN;
int getmaxleft(TreeNode* root, int& depth) {
// 2 确定终止条件
if (root->left == nullptr && root->right == nullptr) {
if (depth > maxdepth) {
maxdepth = depth;
result = root->val;
}
}
if (root->left) {
depth++;
getmaxleft(root->left, depth);
depth--; // 因为这是需要遍历左子树之后又要遍历右子树,需要退回深度
}
if (root->right) {
depth++;
getmaxleft(root->right, depth);
depth--; // 因为这是需要遍历左子树之后又要遍历右子树,需要退回深度
}
return result;
}
int findBottomLeftValue(TreeNode* root) {
int depth=0;
return getmaxleft(root, depth); }
};
106.从中序与后序遍历序列构造二叉树 先找到根节点,再根据中序和后序找到左右子树
TreeNode* Get11(vector<int>& inorder, vector<int>& postorder) {
if (postorder.size() == 0)
return nullptr;
int mid11 = postorder[postorder.size() - 1]; // 中
TreeNode* root = new TreeNode(mid11);
if (postorder.size() == 1)
return root;
int val;
for (val = 0; val < inorder.size(); val++) {
if (inorder[val] == mid11)
break;
// inorder.size()-val-
} // 获取了中序的索引
// vector<int> inorder2 {inorder.begin(),inorder.begin()+val}//left
// inorder.begin()+val+1,inorder.end()right
// vector<int> postorder2
// ={postorder.begin(),postorder.begin()+val}left
// postorder.begin()+val,postorder.end()-1right
vector<int> inorderleft = {inorder.begin(), inorder.begin() + val};
vector<int> inorderright = {inorder.begin() + val + 1, inorder.end()};
vector<int> postorderleft = {postorder.begin(),
postorder.begin() + val};
vector<int> postorderright = {postorder.begin() + val,
postorder.end() - 1};
root->left = Get11(inorderleft, postorderleft);
root->right = Get11(inorderright, postorderright); return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return Get11(inorder, postorder);
}
112. 路径总和 终止条件是到叶子节点并且为0的时候,而处理的逻辑就是先减去当前val,再判断这条路径是否存在
// 左中右,中序:如果一边大于sum那就不要了直接return
// 递归三部曲:
// 1确定返回值和参数
bool IsCan(TreeNode* root, int num) {
// 2终止条件:
if (root->left == nullptr && root->right == nullptr) {
if(num==0)
return true;else return false;
}
// if(root->left == nullptr && root->right == nullptr&&num!=0)return false;
if (root->left) {
num -= root->left->val;
if (IsCan(root->left, num))
return true;
num += root->left->val;
}
if (root->right) {
num -= root->right->val;
if (IsCan(root->right, num))
return true;
num += root->right->val;
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root==nullptr)return false;
return IsCan(root,targetSum-root->val);
}