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
  • 相关阅读:
    KINDLE 小说下载--超级书库
    修改PR Cs6,PS Cs6,AU Cs6的启动界面
    SQLMAP用户手册
    Burp Suite 实战指南--说明书
    XSS跨站测试代码
    万能密码字典
    python数据结构之队列(一)
    python数据结构之栈
    python实现链表(二)
    python实现链表(一)
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8624718.html
Copyright © 2011-2022 走看看