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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its depth = 3.

在真实的面试中遇到过

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

递归算 =子树的层数 +1;

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

找了排行榜上第一的非递归算法

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root==NULL)
            return 0;

        queue<pair<TreeNode*,int>> que;  
        pair<TreeNode*,int> p;
        que.push(make_pair(root,1));

        while(!que.empty())
        {
            p=que.front();
            if(p.first->left)
                que.push(make_pair(p.first->left,p.second+1));
            if(p.first->right)
                que.push(make_pair(p.first->right,p.second+1));
            que.pop();
        }
        return p.second;     
    }
};