剑指Offer 55 I、II

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

题目描述

在这里插入图片描述

菜鸡思考:

我们使用从下向上的思想。最后NULL的时候返回零,那么每次加1,返回左右子树的最大值加1,就是我们该节点最大的深度,即我们该节点的深度。

菜鸡代码:

/**
 * 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) {
    
    
            return 0;
        }
        int a = maxDepth(root->left) + 1;
        int b = maxDepth(root->right) + 1;
        return (a > b ? a : b);
    }
};

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

题目描述

在这里插入图片描述

菜鸡思考:

这个就是继续上一题的思想,判断左右子树的高度,大于一就不是平衡二叉树。

菜鸡代码:

class Solution {
    
    
public:
    bool flag = true;
    int maxDepth(TreeNode* root) {
    
    
        if (!root) {
    
    
            return 0;
        }
        int a = maxDepth(root->left) + 1;
        int b = maxDepth(root->right) + 1;
        if ((a - b > 1) || (b - a > 1)) {
    
    
            flag = false;
        }
        return (a > b ? a : b);
    }
    bool isBalanced(TreeNode* root) {
    
    
        maxDepth(root);
        return flag;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_52192405/article/details/124594175