231. 2的幂

题目:https://leetcode-cn.com/problems/power-of-two/

解法一:n & (n-1)

class Solution {
public:
    bool isPowerOfTwo(int n) {
        return n > 0 && !(n & (n - 1));
    }
};

解法二:lowbit(x)

class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & -n) == n;
    }
}

235. 二叉搜索树的最近公共祖先

题目:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

解法一:递归解法

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==nullptr) return nullptr;
        if(root->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left,p,q);
        if(root->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right,p,q);
        return root;
    }
};

解法二:非递归解法

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==nullptr || p==nullptr || q==nullptr) return nullptr;
        while(true){
            if(root->val > p->val && root->val > q->val) root = root->left;
            else if(root->val < p->val && root->val < q->val) root = root->right;
            else return root;

        }
        return nullptr;
    }
};
  1. 注意问题题设条件为二叉搜索树,二叉树的特点即节点值L<M<R。所以我们要找两个节点的祖先节点,即从根开始遍历,找到最先出现的第一个满足条件的节点即他们的最近公共祖先。主要有如下几种情况进行讨论

236. 二叉树的最近公共祖先

题目:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/

解法一:暴力递归