leetcode-master/problems/0110.平衡二叉树.md

2.8 KiB
Raw Blame History

题目地址

https://leetcode-cn.com/problems/balanced-binary-tree/

思路

递归三步曲分析:

  1. 明确递归函数的参数和返回值

参数的话为传入的节点指针,就没有其他参数需要传递了,返回值要注意,我们的返回值是要求传入节点为根节点树的深度否则如何标记左右子树是否差值大于1呢。

这里还要注意一点,如果当前传入节点为根节点的二叉树已经不是二叉平衡树了,返回高度还有意义么? 此时可以返回-1 来标记已经不符合平衡树的规则了。

代码如下:

int depth(TreeNode* node)
  1. 明确终止条件

递归的过程中依然是遇到空节点了为终止返回0表示当前节点为根节点的书高度为0

代码如下:

if (node == NULL) {
    return 0;
}
  1. 明确单层递归的逻辑

如何判断当前传入节点为根节点的二叉树是否是平衡二叉树呢,当然是左子树高度和右子树高度相差。

分别求出左右子树的高度然后如果差值小于等于1则返回当前二叉树的高度否则则返回-1表示已经不是二叉树了。

代码如下:

int leftDepth = depth(node->left);
if (leftDepth == -1) return -1;
int rightDepth = depth(node->right);
if (rightDepth == -1) return -1;
return abs(leftDepth - rightDepth) > 1 ? -1 : 1 + max(leftDepth, rightDepth);

此时递归的函数就已经写出来了,这个递归的函数传入节点指针,返回以该节点为根节点的二叉树的高度,如果不是二叉平衡树了则返回-1。

代码如下:

int depth(TreeNode* node) {
    if (node == NULL) {
        return 0;
    }
    int leftDepth = depth(node->left);
    if (leftDepth == -1) return -1;
    int rightDepth = depth(node->right);
    if (rightDepth == -1) return -1;
    return abs(leftDepth - rightDepth) > 1 ? -1 : 1 + max(leftDepth, rightDepth);
}

整体代码如下:

C++代码

class Solution {
public:
    // 返回以该节点为根节点的二叉树的高度,如果不是二叉搜索树了则返回-1
    int depth(TreeNode* node) {
        if (node == NULL) {
            return 0;
        }
        int leftDepth = depth(node->left);
        if (leftDepth == -1) return -1; // 说明左子树已经不是二叉平衡树
        int rightDepth = depth(node->right);
        if (rightDepth == -1) return -1; // 说明右子树已经不是二叉平衡树
        return abs(leftDepth - rightDepth) > 1 ? -1 : 1 + max(leftDepth, rightDepth);
    }
    bool isBalanced(TreeNode* root) {
        return depth(root) == -1 ? false : true; 
    }
};

更多算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。