LeetCode (Maximum Depth of Binary Tree)

来源:互联网 发布:实物期权 知乎 编辑:程序博客网 时间:2024/06/06 12:39

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.

Solution1:

/** * 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) return 0;        return 1 + max(maxDepth(root->left), maxDepth(root->right));    }};

Solution2:

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