码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-04-12 00:07:49      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:ret   pop   str   tree node   ++   递归   深度   turn   bin   

二叉树最大深度

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;
    }
};

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

标签:ret   pop   str   tree node   ++   递归   深度   turn   bin   

原文地址:https://www.cnblogs.com/Trevo/p/12682936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!