劍指offer:數字在排序數組中出現的次數&二叉樹的深度&平衡二叉樹

37.數字在排序數組中出現的次數

/*
題目描述
統計一個數字在排序數組中出現的次數。
*/
class Solution {
public:
    int GetNumberOfK(vector<int> data ,int k) {
        if(data.empty())
            return 0;
        int num = 0;
        for(int i = 0; i < data.size(); i++)
        {
            if(data[i] == k)
                num++;
        }
        return num;
    }
};

38.二叉樹的深度

/*
題目描述
輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度
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 == nullptr)
            return 0;
        int leftLength = TreeDepth(pRoot->left);
        int rightLength = TreeDepth(pRoot->right);
        return leftLength>rightLength?leftLength+1:rightLength+1;
    }
};

39.平衡二叉樹

class Solution {
public:
    int getDepth(TreeNode *pRoot)
    {
        if (pRoot == nullptr)
            return 0;
        int leftDepth = getDepth(pRoot->left);
        int rightDepth = getDepth(pRoot->right);
        return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
    }
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if (pRoot == nullptr)
            return true;
        int leftDepth = getDepth(pRoot->left);
        int rightDepth = getDepth(pRoot->right);
        if (abs(leftDepth - rightDepth) > 1)
            return false;
        return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章