zoukankan      html  css  js  c++  java
  • LeetCode 其他题目记录

    104. Maximum Depth of Binary Tree

    和111很像,只是递归的结构略有不同,可简单画图分析,求最大深度可以直接返回1+max(左子树深度,右子树深度),但是求最小深度时不可以,需要分别考虑左右子树为空的情况。可以举个反例子,比如,单斜树。

    1 class Solution {
    2 public:
    3     int maxDepth(TreeNode* root) {
    4         if (!root) return 0;
    5         return 1 + max(maxDepth(root->left), maxDepth(root->right));
    6     }
    7 };
    View Code

    111. Minimum Depth of Binary Tree

    递归的典型应用,分清终止条件

     1 /**
     2  * Definition for binary tree
     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 minDepth(TreeNode *root) {
    13         if (root == NULL) return 0;
    14         if (root->left == NULL && root->right == NULL) return 1;
    15         
    16         if (root->left == NULL) return minDepth(root->right) + 1;
    17         else if (root->right == NULL) return minDepth(root->left) + 1;
    18         else return 1 + min(minDepth(root->left), minDepth(root->right));
    19     }
    20     
    21 };
    View Code
  • 相关阅读:
    .NET 动态向Word文档添加数据
    .NET FileUpLoad上传文件
    Jquery 客户端生成验证码
    ASP.NET MVC 5 基本构成
    .NET 发布网站步骤
    Jquery 选择器大全
    .NET 知识整理笔记
    .NET 三层架构
    C#知识整理笔记
    .NET MD5加密解密代码
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8624718.html
Copyright © 2011-2022 走看看