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
  • 相关阅读:
    python实训day8
    python实训day7
    python实训day6
    python实训day5
    python实训day4
    python实训day3
    python实训day2
    python实训day1
    MyBatis入门-insert标签介绍及使用
    Shell入门-Shell脚本开发规范
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8624718.html
Copyright © 2011-2022 走看看