递归求树的深度,判断是否是平衡树

求树的深度

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot == NULL) return 0;

        int left = TreeDepth(pRoot->left);
        int right = TreeDepth(pRoot->right);

        return (left>right) ? left+1: right+1;

    }
};

判断是否是平衡树

class Solution {
public:
    int TreeDepth(TreeNode* pRoot){
        if(pRoot == NULL) return 0;

        int left = TreeDepth(pRoot->left);
        int right = TreeDepth(pRoot->right);

        return (left>right)? left+1: right+1;
    }

    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot == NULL) return true;

        int leftNum = TreeDepth(pRoot->left);
        int rightNum = TreeDepth(pRoot->right);

        if(abs(leftNum-rightNum)>1)
            return false;

        return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
    }
};
以下是判断二叉是否为平衡二叉的C++代码实现: ```c++ #include <iostream> #include <algorithm> using namespace std; // 定义二叉节点 struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; // 判断是否为平衡二叉 bool isBalanced(TreeNode* root) { if (root == NULL) { return true; } // 计算左右子深度 int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); // 判断左右子深度差是否大于1,如果大于1则不是平衡二叉 if (abs(leftDepth - rightDepth) > 1) { return false; } // 递归判断左右子是否都是平衡二叉 return isBalanced(root->left) && isBalanced(root->right); } // 计算深度 int maxDepth(TreeNode* root) { if (root == NULL) { return 0; } int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); return max(leftDepth, rightDepth) + 1; } int main() { TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->left = new TreeNode(4); root->left->right = new TreeNode(5); root->left->right->left = new TreeNode(6); if (isBalanced(root)) { cout << "This is a balanced binary tree." << endl; } else { cout << "This is not a balanced binary tree." << endl; } return 0; } ``` 算法思路: 1. 首先计算二叉深度,可以使用递归的方式求解; 2. 然后分别计算左右子深度判断深度差是否大于1; 3. 如果深度差大于1,则不是平衡二叉,直接返回false; 4. 如果深度差小于等于1,则需要继续递归判断左右子是否都是平衡二叉,如果都是平衡二叉,则返回true,否则返回false。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值