算法-求二叉树的最大深度

1.题目
求给定二叉树的最大深度(最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量)(代码在牛客网上通过)
2.思路
3.代码
/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    /*
    方法一:层序遍历
    */
    int maxDepth(TreeNode* root) {
        queue<TreeNode*> res;
        queue<int> num;
        int numb = 0;
        res.push(root);
        TreeNode* cur = root;
        if(!root){
            numb = 0;
            return numb;
        }
        while(!res.empty()){
            numb++;
            int len = res.size();
            for(int i=0;i<len;i++){
                cur = res.front();
                res.pop();
                if(cur->left) res.push(cur->left);
                if(cur->right) res.push(cur->right);
            }
        }
        return numb;
    }
    
    /*
    方法二:递归
    */
    int maxDepth(TreeNode* root) {
        if(!root){
            return 0;
        }
        return 1+std::max(maxDepth(root->left),maxDepth(root->right));
    }
};

 

 

posted on 2020-09-13 21:57  ioYuki  阅读(542)  评论(0编辑  收藏  举报

导航