首页 > 其他分享 >剑指 Offer 55 - I. 二叉树的深度(简单)

剑指 Offer 55 - I. 二叉树的深度(简单)

时间:2023-08-19 13:22:08浏览次数:37  
标签:return cur Offer 55 max traversal int depth 二叉树

题目:

class Solution {
public:
    void traversal(TreeNode* cur, int& max, int depth){    //max用来记录最长路径长度,depth记录当前路径长度
        if(!cur) return;
        depth++;
        if(depth>max) max = depth;
        traversal(cur->left, max, depth);
        traversal(cur->right, max, depth);
    }
    int maxDepth(TreeNode* root) {
        int max = 0;
        if(!root) return max;
        traversal(root, max, 0);
        return max;
    }
};

标签:return,cur,Offer,55,max,traversal,int,depth,二叉树
From: https://www.cnblogs.com/fly-smart/p/17642361.html

相关文章

  • 剑指 Offer 54. 二叉搜索树的第k大节点
    方法一:由于是有序的平衡二叉树,因此是中序。根据dfs中序迭代求得递增排序后,再反转就可求得结果。classSolution{public:vector<int>tmp;intkthLargest(TreeNode*root,intk){//if(root!=NULL)returndfs(root);reverse(tmp.be......
  • 合并二叉树
    力扣(LeetCode)官网-全球极客挚爱的技术成长平台经验1:程序写在递归函数前面代表压栈的时候实现,也就是说浏览到这个结点的时候实现程序写在递归函数后面代表弹栈的时候实现,也就是下一次递归结束后在本次递归函数中实现那么到底是压栈的时候实现还是弹栈的时候实现呢,这要看对根......
  • 剑指 Offer 36. 二叉搜索树与双向链表
    本题比较重要的有两点:1.一般认为有序的二叉搜索树,都是中序遍历。2.中序遍历的递归顺序,得到的就是排好序的,就是链表的顺序,因此只需管遍历的过程中的链表指向即可。classSolution{public://pre将来指向尾节点,head指向头节点Node*pre=nullptr,*head=nullptr;......
  • 剑指 Offer 16. 数值的整数次方(中等)
    题目classSolution{public:doubletraversal(doublex,intn){if(n==0)return1.00000;doubley=traversal(x,n/2);//本题需要对递归时的指数进行二分法,否则超时。returnn%2==0?y*y:y*y*x;//y=(x^4)。n=8,则x^8=y*y;n......
  • 剑指 Offer 34. 二叉树中和为某一值的路径
    dfsclassSolution{public:vector<vector<int>>res;vector<int>tmp;voiddfs(TreeNode*node,inttarget){if(node==nullptr)return;target-=node->val;tmp.emplace_back(node->val);......
  • [LeetCode][55]jump-game
    ContentYouaregivenanintegerarraynums.Youareinitiallypositionedatthearray'sfirstindex,andeachelementinthearrayrepresentsyourmaximumjumplengthatthatposition.Returntrueifyoucanreachthelastindex,orfalseotherwise.......
  • LeetCode[55]JumpGame
    ContentYouaregivenanintegerarraynums.Youareinitiallypositionedatthearray'sfirstindex,andeachelementinthearrayrepresentsyourmaximumjumplengthatthatposition.Returntrueifyoucanreachthelastindex,orfalseotherwise.......
  • No_55_JumpGame
    ContentYouaregivenanintegerarraynums.Youareinitiallypositionedatthearray'sfirstindex,andeachelementinthearrayrepresentsyourmaximumjumplengthatthatposition.Returntrueifyoucanreachthelastindex,orfalseotherwise.......
  • 判断是否为完全二叉树
    利用层次遍历思想,但结点是否为空不影响入队。当出队时,该结点为空,若队列中仍有不为空的结点,则不是完全二叉树空树也是完全二叉树#include<stdio.h>#include<stdlib.h>#defineMaxSize100typedefstructNode{intdata;structNode*lchild,*rchild;}TreeNode......
  • 【剑指Offer】61、序列化二叉树
    【剑指Offer】61、序列化二叉树题目描述:请实现两个函数,分别用来序列化和反序列化二叉树。解题思路:序列化是指将结构化的对象转化为字节流以便在网络上传输或写到磁盘进行永久存储的过程。反序列化是指将字节流转回结构化的对象的过程,是序列化的逆过程。受第4题:重建二叉树的启......