Maximum Depth of Binary Tree

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxdepth=0;
    int tempdepth=0;
    int findMaxDepth(TreeNode* root)
    {
                tempdepth+=1;
        if(root->left!=NULL){ this->findMaxDepth(root->left); tempdepth-=1; }
       
        if(root->right!=NULL) {this->findMaxDepth(root->right); tempdepth-=1;}
        maxdepth=tempdepth>maxdepth?tempdepth:maxdepth;
        return 0;
        
    }
    int maxDepth(TreeNode* root) {
        if(root==NULL) return 0;
        findMaxDepth(root);
        return maxdepth;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *

曠怡亭口占

流轉知何世,江山尚此亭。

登臨皆曠士,喪亂有遺經。

已識乾坤大,猶憐草木青。

長空送鳥印,留幻與人靈。

Featured Posts