LeetCode#104二叉树的最大深度

104.二叉树的最大深度标题

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

2.层序遍历

/**
 * 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;
        queue<TreeNode*> quetree;
        quetree.push(root);
        int dep=0;
        while(!quetree.empty()){
            int sz=quetree.size();
            while(sz>0){
                TreeNode * node=quetree.front();
                quetree.pop();
                if(node->left) quetree.push(node->left);
                if(node->right) quetree.push(node->right);
                sz--;
            } 
            dep++;
        }
        return dep;
    }
};
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页