【剑指offer】【树】55-I.二叉树最大深度

题目链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/

DFS(递归法)

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

BFS(借助队列)

/**
 * 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 *> q;
        q.push(root);
        int res = 0;
        while(!q.empty())
        {
            int n = q.size();
            while(n--)
            {
                TreeNode* tmp = q.front();
                q.pop();
                if(tmp -> left) q.push(tmp -> left);
                if(tmp -> right) q.push(tmp -> right);
            }
            res++;
        }
        return res;
    }
};
posted @ 2020-04-11 23:04  NaughtyCoder  阅读(82)  评论(0)    收藏  举报