0
点赞
收藏
分享

微信扫一扫

摸鱼日记1.29

闲云困兽 2022-01-30 阅读 45

学习目标:

搜索与回溯算法

学习内容:

剑指 Offer 55 - I. 二叉树的深度

DFS

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
  int maxDepth(TreeNode *root) {
    if (root == NULL)
      return 0;
    return 1 + max(maxDepth(root->left), maxDepth(root->right));
  }
};

剑指 Offer 55 - II. 平衡二叉树

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
  bool isBalanced(TreeNode *root) {
    if (root == NULL)
      return true;
    if (abs(maxDepth(root->left) - maxDepth(root->right)) > 1) {
      return false;
    }
    return isBalanced(root->left) && isBalanced(root->right);
  }

  int maxDepth(TreeNode *root) {
    if (root == NULL)
      return 0;
    return 1 + max(maxDepth(root->left), maxDepth(root->right));
  }
};

我好了,谢谢田田,

举报

相关推荐

摸鱼日记2.15

摸鱼日记2.5

摸鱼日记2.20

摸鱼日记1.24

摸鱼日记1.19

摸鱼日记1.31

1.29 Registration System

0 条评论