[Daily question] The maximum depth of the binary tree

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

Depth = max (left, right)

1. Recursion

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. Non-recursive

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 original articles have been published · 91 praises · 40,000+ views

Guess you like

Origin blog.csdn.net/Hanoi_ahoj/article/details/105500223