Maximum Depth of Binary Tree @LeetCode

PROBLEM :

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
 
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :(Recursive Solution - Actually Depth-first-search)
--------------------------------------------------------------------------------

/**
 * 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 l=maxDepth(root->left) ;
        int r=maxDepth(root->right) ;
     
        return l>r?l+1:r+1 ;
     
    }
};

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :(Iterative Solution - using Queue STL - Actually Breadth-first-search)
--------------------------------------------------------------------------------

/**
 * 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 ;
         
        queue<TreeNode*> que ;
        que.push(root) ;
        int depth=0 ;
     
        while(!que.empty()){
            depth++ ;
            int n=que.size() ;
            for(int i=0;i<n;i++){
                TreeNode* temp=que.front() ;
                que.pop() ;
             
                if(temp->left)
                    que.push(temp->left) ;
                if(temp->right)
                    que.push(temp->right) ;
            }
        }
        return depth ;
    }
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )