Maximum Depth of Binary Tree

non-recursion/traverse

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int depth = 0,max = 0;

    void helper(TreeNode* root,int depth){
        if(root == NULL) return ;

        depth++;
        if(depth > max){
            max = depth;
        }

        helper(root->left,depth);

        helper(root->right,depth);
    }
    int maxDepth(TreeNode* root) {
       helper(root,depth);
       return max;
    }
};

recursion

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL)
            return 0;

        int leftDepth = maxDepth(root->left) + 1;
        int rightDepth = maxDepth(root->right) + 1;

        return max(leftDepth,rightDepth);
    }
};