[毎日の質問]二分木の最大深度

タイトル:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

奥行き=最大(左、右)

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

98件のオリジナル記事が公開されました 91件の賞賛 40,000回以上の閲覧

おすすめ

転載: blog.csdn.net/Hanoi_ahoj/article/details/105500223