剑指offer 面试题55 - I. 二叉树的深度——递归/层次

我的解题:

1.最喜欢用层次遍历,,,所以还是这个方法,queue里保存的是pair

  queue<pair<TreeNode*,int>> q;  int是所在的层数

class Solution {
public:
    int maxDepth(TreeNode* root) {
        queue<pair<TreeNode*,int>> q;
        if(!root)   return 0;
        q.push(make_pair(root,1));
        int level=1;
        while(!q.empty()){
            auto [tmp,now]=q.front();
            q.pop();
            if(tmp==NULL)   continue;
            level=max(level,now);
            q.push(make_pair(tmp->right,now+1));
            q.push(make_pair(tmp->left,now+1));
        }
        return level;
    }
};

2.递归

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root)   return NULL;
        return max(maxDepth(root->right),maxDepth(root->left))+1;
    }
};

发布了76 篇原创文章 · 获赞 1 · 访问量 588

猜你喜欢

转载自blog.csdn.net/qq_41041762/article/details/105578761
今日推荐