• LeetCode 104. 二叉树的最大深度


    题目链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

    给定一个二叉树,找出其最大深度。

    二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

    说明: 叶子节点是指没有子节点的节点。

    示例:
    给定二叉树 [3,9,20,null,null,15,7],

    3
    /
    9 20
    /
    15 7
    返回它的最大深度 3 。

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     struct TreeNode *left;
     6  *     struct TreeNode *right;
     7  * };
     8  */
     9 int maxDepth(struct TreeNode* root){
    10     if(root==NULL) return 0;
    11     if(root->left==NULL&&root->right==NULL) return 1;
    12     int a=0,b=0;
    13     if(root->left!=NULL){
    14         a=1+maxDepth(root->left);
    15     }
    16     if(root->right!=NULL){
    17         b=1+maxDepth(root->right);
    18     }
    19     return a>b?a:b;
    20 }

     again:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int maxDepth(TreeNode* root) {
    13         if(root==NULL) return 0;
    14         if(root->left==NULL&&root->right==NULL) return 1;
    15         int x=maxDepth(root->right);
    16         int y=maxDepth(root->left);
    17         return x>y?x+1:y+1;
    18     }
    19 };
  • 相关阅读:
    内部类
    抽象类与接口
    多态
    继承
    封装
    创建对象的内存分析
    构造器
    面向对象 类与对象
    uniapp跳转
    uniapp-组件引用错误,仅支持 import 方式引入组件
  • 原文地址:https://www.cnblogs.com/shixinzei/p/11349669.html
Copyright © 2020-2023  润新知