【Day9】二叉树遍历专题(层序遍历、最大深度、路径总和)

【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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值