【Day9】二叉树遍历专题2
层序遍历
class Solution{
public:
vector<vector<int>> levelOrder(TreeNode* root){
queue<TreeNode*> q;
vector<vector<int>> ans;
if(root == nullptr)return {};
q.push(root);
while(!q.empty()){
int n = q.size();
vector<int> value;
for(int i = 0;i<n;++i){
TreeNode * node = q.front();
q.pop();
value.push_back(node->val);
if(node->left)q.push(node->left);
if(node->right)q.push(node->right);
}
ans.push_back(value);
}
return ans;
}
};
最大深度
层序遍历:
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*> q;
if(root == nullptr)return 0;
q.push(root);
int ans = 0;
while(!q.empty()){
int n = q.size();
ans ++;
for(int i = 0;i < n;i++){
TreeNode* node = q.front();
q.pop();
if(node->left)q.push(node->left);
if(node->right)q.push(node->right);
}
}
return ans;
}
};
递归:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr)return 0;
int l_dps = maxDepth(root->left);
int r_dps = maxDepth(root->right);
return max(l_dps,r_dps) + 1;
}
};
迭代:
class Solution {
int ans = 0;
void dfs(TreeNode * root,int cnt){
if(root == nullptr)return;
cnt++;
ans = max(cnt,ans);
if(root->left)dfs(root->left,cnt);
if(root->right)dfs(root->right,cnt);
}
public:
int maxDepth(TreeNode* root) {
dfs(root,0);
return ans;
}
};
路径总和
class Solution {
bool dfs(TreeNode* root, int targetSum) {
if (root == nullptr) return false;
int minus = targetSum - root->val;
if (root->left == nullptr && root->right == nullptr && minus == 0) return true;
return dfs(root->left, minus) || dfs(root->right, minus);
}
public:
bool hasPathSum(TreeNode* root, int targetSum) {
return dfs(root,targetSum);
}
};
//精简
class Solution {
public:
bool hasPathSum(TreeNode *root, int targetSum) {
if (root == nullptr) {
return false;
}
targetSum -= root->val;
if (root->left == root->right) { // root 是叶子
return targetSum == 0;
}
return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);
}
};
作者:灵茶山艾府
链接:https://leetcode.cn/problems/path-sum/solutions/2731531/jian-ji-xie-fa-pythonjavacgojsrust-by-en-icwe/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。