Max Depth of Binary Tree

https://leetcode.com/explore/learn/card/data-structure-tree/17/solve-problems-recursively/534/

/**
 * 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:
    // recursive Bottom-Up
    int maxDepth(TreeNode* root) {
        //DFS
        return root == NULL ? 0 : max( maxDepth(root -> left), maxDepth(root -> right) ) + 1;        
    }
    int answer;               // don't forget to initialize answer before call maximum_depth
void maximum_depth(TreeNode* root, int depth) {
    if (!root) {
        return;
    }
    if (!root->left && !root->right) {
        answer = max(answer, depth);
    }
    maximum_depth(root->left, depth + 1);
    maximum_depth(root->right, depth + 1);
}
    //BFS iterative
    int maxDepth(TreeNode *root) {
    if(root == NULL)
        return 0;

    int res = 0;
    queue<TreeNode *> q;
    q.push(root);
    while(!q.empty())
    {
        ++ res;
        for(int i = 0, n = q.size(); i < n; ++ i)
        {
            TreeNode *p = q.front();
            q.pop();

            if(p -> left != NULL)
                q.push(p -> left);
            if(p -> right != NULL)
                q.push(p -> right);
        }
    }

    return res;
    }

results matching ""

    No results matching ""