【每日一題】二叉樹的最大深度

題目:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

深度 = max(左, 右)

1、遞歸

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        if (root->left == nullptr && root->right == nullptr) return 1;

        return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
};

2、非遞歸

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int max_dept = 0;
        queue<pair<TreeNode*,int> >q;
        q.push({root, 1});
        while(!q.empty()) {
            TreeNode* curr_node = q.front().first;
            int curr_dept = q.front().second;
            q.pop();
            if(curr_node) {
                max_dept =  max(curr_dept, max_dept);
                q.push({curr_node->left, curr_dept+1});
                q.push({curr_node->right, curr_dept+1});
            }
        }
        return max_dept;
    }
};

EOF

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章