LeetCode刷题笔记 104. 二叉树的最大深度

题目要求

104. 二叉树的最大深度

题解

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/cde-san-chong-fang-fa-shi-xian-you-zhu-jie-by-zzxh/

递归

当前高度=max(左子树高度,右子树高度)+1

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root) return 0;
        return max(maxDepth(root->left),maxDepth(root->right))+1;        
    }
};
执行用时 内存消耗
20 ms 19.8 MB

深度优先:用栈的循环版

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root==NULL) return 0;
        stack<pair<TreeNode*,int>> s;
        TreeNode* p=root;
        int Maxdeep=0;
        int deep=0;
        while(!s.empty()||p!=NULL)//若栈非空,则说明还有一些节点的右子树尚未探索;若p非空,意味着还有一些节点的左子树尚未探索
        {
            while(p!=NULL)//优先往左边走
            {
                s.push(pair<TreeNode*,int>(p,++deep));
                p=p->left;
            }
            p=s.top().first;//若左边无路,就预备右拐。右拐之前,记录右拐点的基本信息
            deep=s.top().second;
            if(Maxdeep<deep) Maxdeep=deep;//预备右拐时,比较当前节点深度和之前存储的最大深度
            s.pop();//将右拐点出栈;此时栈顶为右拐点的前一个结点。在右拐点的右子树全被遍历完后,会预备在这个节点右拐
            p=p->right;
        }
        return Maxdeep;
    }
};
执行用时 内存消耗
20 ms 19.4 MB

广度优先:使用队列

class Solution {
public:
    int maxDepth(TreeNode* root) {
         if(root==NULL) return 0;
         deque<TreeNode*> q;
         q.push_back(root);
         int deep=0;
         while(!q.empty())
         {
             deep++;
             int num=q.size();  //q.size()会变化,要先保存
             for(int i=0;i<num;i++)
             {
                TreeNode* p=q.front();
                q.pop_front();
                if(p->left) q.push_back(p->left);
                if(p->right) q.push_back(p->right);
             }
         }
         return deep;         
    }
};
执行用时 内存消耗
16 ms 19.4 MB

语法学习

pair

C++ pair的基本用法总结(整理)

deque

C++ deque的总结
[C++ STL] deque使用详解

发布了18 篇原创文章 · 获赞 0 · 访问量 1781

猜你喜欢

转载自blog.csdn.net/g534441921/article/details/104226377