【算法与数据结构】110、LeetCode平衡二叉树

所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解

一、题目

在这里插入图片描述
在这里插入图片描述

二、解法

  思路分析:二叉树遍历一共有前中后遍历和层序遍历,这道题只有后序遍历适合,求深度是从上往下查,求高度是从下往上查,因此后序遍历适合。这里利用了笔者的另外一篇文章的后序遍历算法【算法与数据结构】144、94、145LeetCode二叉树的前中后遍历(递归法、迭代法)。在这个后序遍历算法的基础上,添加了计算节点高度的函数,calc_height函数使用了递归法。首先要知道节点高度等于左右节点高度取最大值+1,这是我们使用递归法计算节点高度的基础:

max(Lheight, Rheight)+1;

递归法的三个要素:1.返回值为节点高度,输入参数为节点变量 2.终止条件为空节点或者是叶子节点 3.单层递归是返回左右节点高度取最大值+1,程序当中可以看到笔者将节点类型分为了五种:

  • 空节点
  • 叶子节点
  • 左节点为空,右节点非空
  • 左节点非空,右节点为空
  • 左右节点均非空
      实际上只有两种,除了空节点这一种类型外,其余四种可以归为一类,单层递归都可以包含在内。但是在LeetCode上跑代码的结果来看,空节点和叶子节点单独列出,直接返回,最节省时间。
      最终程序如下
class Solution {
public:
    // 递归法 三步法:1 、确定返回值和输入参数 2、 确定终止条件 3、确定单层递归逻辑
    int calc_height(TreeNode* root) {   // 计算节点高度
        if (!root) return 0;                            // 1.空节点高度为0
        else if (!(root->left) && !(root->right)) return 1;  // 2.碰到叶子节点返回,叶子节点高度为1
        //else if (!(root->left) && root->right) return 1 + calc_height(root->right);   // 3.左节点为空,右节点非空
        //else if (root->left && !(root->right)) return 1 + calc_height(root->left);   // 4.左节点非空,右节点为空
        else return 1 + max(calc_height(root->left), calc_height(root->right));
    }
    bool isBalanced(TreeNode* root) {
        // 后序遍历,统一风格写法
        stack<TreeNode*> st;
        if (root != NULL) st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();
            if (node != NULL) {
                st.pop();
                st.push(node);                          // 中
                st.push(NULL);
                if (node->right) st.push(node->right);  // 右
                if (node->left) st.push(node->left);    // 左
            }
            else {
                st.pop();
                node = st.top();
                st.pop();
                if (abs(calc_height(node->left) - calc_height(node->right)) > 1) return false;
            }
        }
        return true;
    }
};

  更为精简的版本程序如下,如果当前节点的左右子树高度差值大于1,那么在计算下去也没有意义了,我们直接返回-1。

class Solution2 {
public:
    // 后序遍历
    int calc_height(TreeNode* root) {
        if (!root) return 0;
        int Lheight = calc_height(root->left);
        if (Lheight == -1) return -1;
        int Rheight = calc_height(root->right);
        if (Rheight == -1) return -1;
        return abs(Lheight - Rheight) > 1 ? -1 : 1 + max(Lheight, Rheight);
    }
    bool isBalanced(TreeNode* root) {
        return calc_height(root) == -1 ? false : true;
    }
};

三、完整代码

# include <iostream>
# include <vector>
# include <queue>
# include <string>
# include <algorithm>
# include <stack>
using namespace std;

// 树节点定义
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    // 递归法 三步法:1 、确定返回值和输入参数 2、 确定终止条件 3、确定单层递归逻辑
    int calc_height(TreeNode* root) {   // 计算节点高度
        if (!root) return 0;                            // 1.空节点高度为0
        else if (!(root->left) && !(root->right)) return 1;  // 2.碰到叶子节点返回,叶子节点高度为1
        //else if (!(root->left) && root->right) return 1 + calc_height(root->right);   // 3.左节点为空,右节点非空
        //else if (root->left && !(root->right)) return 1 + calc_height(root->left);   // 4.左节点非空,右节点为空
        else return 1 + max(calc_height(root->left), calc_height(root->right));
    }
    bool isBalanced(TreeNode* root) {
        // 后序遍历,统一风格写法
        stack<TreeNode*> st;
        if (root != NULL) st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();
            if (node != NULL) {
                st.pop();
                st.push(node);                          // 中
                st.push(NULL);
                if (node->right) st.push(node->right);  // 右
                if (node->left) st.push(node->left);    // 左
            }
            else {
                st.pop();
                node = st.top();
                st.pop();
                if (abs(calc_height(node->left) - calc_height(node->right)) > 1) return false;
            }
        }
        return true;
    }
};

class Solution2 {
public:
    // 后序遍历
    int calc_height(TreeNode* root) {
        if (!root) return 0;
        int Lheight = calc_height(root->left);
        if (Lheight == -1) return -1;
        int Rheight = calc_height(root->right);
        if (Rheight == -1) return -1;
        return abs(Lheight - Rheight) > 1 ? -1 : 1 + max(Lheight, Rheight);
    }
    bool isBalanced(TreeNode* root) {
        return calc_height(root) == -1 ? false : true;
    }
};

void my_print(vector <string>& v, string msg)
{
    cout << msg << endl;
    for (vector<string>::iterator it = v.begin(); it != v.end(); it++) {
        cout << *it << "  ";
    }
    cout << endl;
}

void my_print2(vector<vector<int>>& v, string str) {
    cout << str << endl;
    for (vector<vector<int>>::iterator vit = v.begin(); vit < v.end(); ++vit) {
        for (vector<int>::iterator it = (*vit).begin(); it < (*vit).end(); ++it) {
            cout << *it << ' '; 
        }
        cout << endl;
    }
}

// 前序遍历迭代法创建二叉树,每次迭代将容器首元素弹出(弹出代码还可以再优化)
void Tree_Generator(vector<string>& t, TreeNode*& node) {
    if (t[0] == "NULL" || !t.size()) return;    // 退出条件
    else {
        node = new TreeNode(stoi(t[0].c_str()));    // 中
        t.assign(t.begin() + 1, t.end());
        Tree_Generator(t, node->left);              // 左
        t.assign(t.begin() + 1, t.end());
        Tree_Generator(t, node->right);             // 右
    }
}

// 层序遍历
vector<vector<int>> levelOrder(TreeNode* root) {
    queue<TreeNode*> que;
    if (root != NULL) que.push(root);
    vector<vector<int>> result;
    while (!que.empty()) {
        int size = que.size();  // size必须固定, que.size()是不断变化的
        vector<int> vec;
        for (int i = 0; i < size; ++i) {
            TreeNode* node = que.front();
            que.pop();
            vec.push_back( node->val);
            if (node->left) que.push(node->left);   
            if (node->right) que.push(node->right);
        }
        result.push_back(vec);
    }
    return result;
}

int main()
{
    vector<string> t = { "3", "9", "NULL", "NULL", "20", "15", "NULL", "NULL", "7", "NULL", "NULL"};   // 前序遍历
    //vector<string> t = { "1", "2", "3", "4", "NULL", "NULL", "4", "NULL", "NULL", "3", "NULL", "NULL", "2", "NULL", "NULL" };   // 前序遍历
    my_print(t, "目标树");
    TreeNode* root = new TreeNode();
    Tree_Generator(t, root);
    vector<vector<int>> tree = levelOrder(root);
    my_print2(tree, "目标树:");
    Solution s1;
    bool result = s1.isBalanced(root);
    cout << "是否平衡:";
    if (result) cout << "是" << endl;
    else cout << "否" << endl;
    system("pause");
    return 0;
}

end

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚安66

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值