代码随想录打卡18天
513. 找树左下角的值
class Solution {
public:int findBottomLeftValue(TreeNode* root) {int res;queue que;if(root!=nullptr) que.push(root);while(!que.empty()){int s=que.size();for(int i=0;ival;if(node->left) que.push(node->left);if(node->right) que.push(node->right);}}return res;}
};
112. 路径总和
class Solution {
public:void pathsum(TreeNode* root,vector&res,vector&path){if(root==nullptr) return;path.push_back(root->val);if(root->left==nullptr&&root->right==nullptr){int sum=0;for(int i=0;ileft) {pathsum(root->left,res,path);path.pop_back();}if(root->right){pathsum(root->right,res,path);path.pop_back();}}bool hasPathSum(TreeNode* root, int targetSum) {vector res;vector path;pathsum(root,res,path);for(int i=0;i
113. 路径总和 II
class Solution {
public:void pathsum(TreeNode* root,vector>&res,vector&path,int &targetSum){if(root==nullptr) return;path.push_back(root->val);if(root->left==nullptr&&root->right==nullptr){int sum=0;for(int i=0;ileft) {pathsum(root->left,res,path,targetSum);path.pop_back();}if(root->right){pathsum(root->right,res,path,targetSum);path.pop_back();}}vector> pathSum(TreeNode* root, int targetSum) {vector> res;vector path;pathsum(root,res,path,targetSum);return res;}
};
106. 从中序与后序遍历序列构造二叉树
class Solution {
public:TreeNode* tree(vector& inorder, vector& postorder) {if(postorder.size()==0) return nullptr;TreeNode* root=new TreeNode(postorder[postorder.size()-1]);if(postorder.size()==1) return root;int index;for(index=0;indexval==inorder[index]) break;}vector leftin(inorder.begin(),inorder.begin()+index);vector rightin(inorder.begin()+index+1,inorder.end());vector leftpo(postorder.begin(),postorder.begin()+index);vector rightpo(postorder.begin()+index,postorder.end()-1);root->left=tree(leftin,leftpo);root->right=tree(rightin,rightpo);return root;}TreeNode* buildTree(vector& inorder,vector& postorder){return tree(inorder,postorder);}
};
105. 从前序与中序遍历序列构造二叉树
class Solution {
public:TreeNode* buildTree(vector& preorder, vector& inorder) {if(preorder.size()==0) return nullptr;TreeNode* root=new TreeNode(preorder[0]);if(preorder.size()==1) return root;int index;for(index=0;indexval==inorder[index]) break;}vector leftin(inorder.begin(),inorder.begin()+index);vector rightin(inorder.begin()+index+1,inorder.end());vector leftpo(preorder.begin()+1,preorder.begin()+1+index);vector rightpo(preorder.begin()+index+1,preorder.end());root->left=buildTree(leftpo,leftin);root->right=buildTree(rightpo,rightin);return root;}
};
需要重新做的题目
106. 从中序与后序遍历序列构造二叉树
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!