LeetCode Q231 Power of Two

Question:

Given an integer, write a function to determine if it is a power of two.

Solution: 12msĀ 

class Solution {
public:
    bool isPowerOfTwo(int n) {
        long testNum = 1;
        while(n >= testNum){
            if (n == testNum) 
                return true;
            testNum <<= 1;
        }
        return false;
    }
};

Kth Smallest Element in a BST

Question:

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Solution:log(n) — 24ms

class Solution {
public:
    int nodes(TreeNode* root) {
        if (NULL == root)
            return 0;
        return nodes(root->left) + nodes(root->right) + 1;
    }
    int kthSmallest(TreeNode* root, int k) {
        int n = nodes(root->left);
        if (n + 1 == k)
            return root->val;
        else if ( n >= k ) 
            return kthSmallest(root->left, k);
        else
            return kthSmallest(root->right, k - n - 1);
    }
};