LeetCode: 继续easy题2

Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

"""
基本想法是队列实现BFS,但是这样得到的结果顺序是反的。
题目输出是二维vector,直接用二维vector好了。先用递归实现DFS求出二叉树的深度,然后继续DFS遍历二叉树。
3 ms, beats 62.51%
time n space n
"""
/**
 * 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 getDepth(TreeNode* root){
        if(root == NULL)
            return 0;
        return max(getDepth(root->left), getDepth(root->right)) + 1;
    }
    void fillVector(vector<vector<int>> & result, TreeNode* root, int level){
        if(root != NULL){
            result[level].push_back(root->val);
            fillVector(result, root->left, level-1);
            fillVector(result, root->right, level-1);
        }
    }
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        int depth = getDepth(root);
        vector<vector<int>> result(depth, vector<int> {});

        fillVector(result, root, depth-1);
        return result;
    }
};

Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

"""
BST: 或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值
递归法。13 ms, beats 50.20%
time n
"""
/**
 * 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* createNode(vector<int>& nums, int start, int end){
        if(start>end)
            return NULL;
        int middle = (start + end)/2;
        TreeNode* temp = new TreeNode(nums[middle]);//
        temp->left = createNode(nums, start, middle-1);
        temp->right = createNode(nums, middle+1, end);
        return temp;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return createNode(nums, 0, nums.size()-1);
    }
};

Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.

"""递归。9 ms beats 23.90%
但是用了两重递归,time nlogn (T(n) = 2T(n/2) + O(n)).
Top down approach
"""
class Solution {
public:
    int depth(TreeNode* root){
        return root == NULL? 0: max(depth(root->left), depth(root->right))+1;
    }
    bool smallThan1(TreeNode* root){
        int d_left = depth(root->left);
        int d_right = depth(root->right);
        return abs(d_left - d_right)<=1;
    }
    bool isBalanced(TreeNode* root) {
        return root == NULL? true: smallThan1(root) && isBalanced(root->left) && isBalanced(root->right);
    }
};
"""bottom up。就是把前面计算节点的深度和比较节点的深度两件事一块干了。
time n, 12 ms, space logn(不要忽略退栈)
"""
class Solution {
public:
    int depth_and_smallThan1(TreeNode* root){
        if (root == NULL) return 0;

        int d_left = depth_and_smallThan1(root->left);
        if (d_left == -1) return -1;
        int d_right = depth_and_smallThan1(root->right);
        if (d_right == -1) return -1;
        if (abs(d_left - d_right) > 1) return -1;

        return max(d_left, d_right) + 1;
    }
    bool isBalanced(TreeNode* root) {
        return root == NULL? true: depth_and_smallThan1(root) != -1;
    }
};

Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth

"""
这些题都差不多。队列实现BFS。
"""
class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root == NULL) return 0;
        queue<TreeNode*> Q;
        Q.push(root);
        int i = 0;
        while (!Q.empty()) {
            i++;
            int k = Q.size();
            for (int j=0; j<k; j++) {
                TreeNode* rt = Q.front();
                if (rt->left) Q.push(rt->left);
                if (rt->right) Q.push(rt->right);
                Q.pop();
                if (rt->left==NULL && rt->right==NULL) return i;
            }
        }
        return -1; 
    }
};

Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum

"""again是二叉树的遍历,直接递归实现。
time n, space n (链表)
"""
 */
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if (root == NULL) return false;
        if (root->val == sum && root->left ==  NULL && root->right == NULL) return true;
        return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
    }
};

Pascal’s Triangle
Given numRows, generate the first numRows of Pascal’s triangle.

"""小时候见过,杨辉三角。
简单,就是对二维vector的操作和初始化啥的。讨论区有各种各样的写法。
time n^2 (等差数列), space n^2
"""
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        if (numRows == 0) return {}; //
        vector<vector<int>> result(numRows, vector<int>{}); //
        for(int i=0; i<numRows; i++){
            result[i].resize(i+1); //
            result[i][0] = 1;
            result[i][i] = 1;
            for(int j=1; j<i; j++){
                result[i][j] = result[i-1][j-1] + result[i-1][j];
            }
        }
        return result;
    }
};

Pascal’s Triangle II
Given an index k, return the kth row of the Pascal’s triangle.

"""同上一题。But need to optimize your algorithm to use only O(k) extra space. 就是每算完一层把上一层的内存释放掉呗。或者直接不断刷新同一块内存(类似inplace的滤波或卷积)。引入previous和current两个变量。
0 ms, beats 45.04%
"""
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        int numRows = rowIndex + 1;  //行数
        vector<int> result(numRows); 
        int previous = 0;
        int current = 0;

        for(int i=0; i<numRows; i++){
            result[0] = 1;
            result[i] = 1;

            previous = result[0];
            for(int j=1; j<i; j++){
                current = result[j];
                result[j] = previous + result[j];
                previous = current;
            }
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值