LeetCode513. 找树左下角的值
题目链接:513. 找树左下角的值 - 力扣(LeetCode)
文章讲解:代码随想录
视频讲解:怎么找二叉树的左下角? 递归中又带回溯了,怎么办?| LeetCode:513.找二叉树左下角的值_哔哩哔哩_bilibili
思路:这道题用层序遍历特别方便(也就是迭代不是递归),我们只需要遍历到最后一行,再获得最左边的节点的值即可。
代码:
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*>que;
int result=0;
if(root!=NULL){
que.push(root);
}
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;
}
};
LeetCode112. 路径总和
题目链接:112. 路径总和 - 力扣(LeetCode)
文章讲解:代码随想录
视频讲解:拿不准的遍历顺序,搞不清的回溯过程,我太难了! | LeetCode:112. 路径总和_哔哩哔哩_bilibili
思路:这道题的重点依然在于回溯,也就是当我们抵达叶子节点时,如果count被一路减为0的话,则直接return true,反之return false,然后在递归左孩子和右孩子时,如果从下面返回true了,则继续return true,否则就需要回溯count。
代码:
class Solution {
public:
bool traversal(TreeNode* node,int count){
if(node->left==NULL&&node->right==NULL&&count==0){
return true;
}
if(node->left==NULL&&node->right==NULL&&count!=0){
return false;
}
if(node->left){
count-=node->left->val;
if(traversal(node->left,count)==true){
return true;
}
count+=node->left->val;
}
if(node->right){
count-=node->right->val;
if(traversal(node->right,count)==true){
return true;
}
count-=node->right->val;
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root==NULL){
return false;
}
return traversal(root,targetSum-root->val);
}
};
LeetCode106. 从中序与后序遍历序列构造二叉树
题目链接:106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)
文章讲解:代码随想录
视频讲解:坑很多!来看看你掉过几次坑 | LeetCode:106.从中序与后序遍历序列构造二叉树_哔哩哔哩_bilibili
思路:这道题比较复杂。主要分为6步,第一步,如果数组大小为0,就说明是空的。第二步,如果数组大小不为0,取后序遍历最后一个值作为根节点的值,然后如果后序遍历只有一个值说明是叶子节点,可以直接return当前节点不需要后续工作。第三步,找到后序遍历最后一个值(root)在中序遍历中的位置。第四步,切分中序遍历为root左孩子的和右孩子的。第五步,根据中序遍历的大小,切分后序遍历的左孩子和右孩子的。第六步,递归左孩子和右孩子。
代码:
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(postorder.size()==0){
return NULL;
}
int rootvalue=postorder[postorder.size()-1];
TreeNode* root=new TreeNode(rootvalue);
if(postorder.size()==1){
return root;
}
int index=0;
for(index=0;index<inorder.size();index++){
if(inorder[index]==rootvalue){
break;
}
}
vector<int>leftinorder(inorder.begin(),inorder.begin()+index);
vector<int>rightinorder(inorder.begin()+index+1,inorder.end());
postorder.resize(postorder.size()-1);
vector<int>leftpostorder(postorder.begin(),postorder.begin()+leftinorder.size());
vector<int>rightpostorder(postorder.begin()+leftinorder.size(),postorder.end());
root->left=buildTree(leftinorder,leftpostorder);
root->right=buildTree(rightinorder,rightpostorder);
return root;
}
};