每日刷題(3)

題目

Leetcode108.將有序數組轉化爲二叉搜索樹

/**
 * 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:
    TreeNode *sort_binary(vector<int>&nums,int l,int r){
        if(l  > r) return NULL;
        TreeNode * root = new TreeNode;
        root->val = nums[(l + r)/2];
        root->left = sort_binary(nums,l,(l + r)/2 - 1);
        root->right = sort_binary(nums,(l + r)/2 + 1,r);
        return root;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
       TreeNode * root;
        root = sort_binary(nums,0,nums.size()-1);
        return root;
    }

};

區分
平衡二叉樹(Balanced Binary Tree具有以下性質:它是一棵空樹或它的左右兩個子樹的高度差的絕對值不超過1,並且左右兩個子樹都是一棵平衡二叉樹。
二叉排序樹(Binary Sort Tree),又稱二叉查找樹(Binary Search Tree),亦稱二叉搜索樹。
一棵空樹,或者是具有下列性質的二叉樹:
(1)若左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;
(2)若右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;
(3)左、右子樹也分別爲二叉排序樹;
(4)沒有鍵值相等的結點。

Leetcode110.平衡二叉樹

/**
 * 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 height(TreeNode *root){  //高度
        if(root == NULL) return 0;
        int a = height(root->left) ;
        int b = height(root->right);
        return max(a,b) + 1;
    }
    bool isBalanced(TreeNode* root) {
        if(root == NULL) return true;
        //需要滿足三個條件1.根的左右子樹高度差小於一   2.左子樹是平衡二叉樹   3.右子樹是平衡二叉樹
        if(abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right)){
            return true;
        }else{
            return false;
        }
    }
};

Leetcode111.二叉樹最小深度

錯誤代碼

/**
 * 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 minDepth(TreeNode* root) {
        if(root == NULL) return 0;
        int a = minDepth(root->left);
        int b = minDepth(root->right);
        return min(a,b) + 1;
    }
};

錯誤案例
[1,2]
在這裏插入圖片描述此題關鍵在於省題,題目中說最小深度是從根節點到最近葉子節點的最短路徑上的節點數量,所以案例[1,2]最小深度是2而不是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 minDepth(TreeNode* root) {
        if(root == nullptr) return 0;
        int a = minDepth(root->left);
        int b = minDepth(root->right);
        if((root->left == nullptr && root->right != nullptr)||(root->left != nullptr && root->right == nullptr)){
            return (a == 0)?(b+1):(a+1); 
        }else{
             return min(a,b) + 1;
        }
    }
};

對比題Leetcode104.二叉樹最大深度

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章