# Save the half which has result

## 162 Find the peak element

A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums\[i] ≠ nums\[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that nums\[-1] = nums\[n] = -∞.

Define peak `A[P] > A[P-1] && A[P] > A[P+1]`

```python
def findPeakElement(self, nums: List[int]) -> int:
    l, r = 0, len(nums)-1
    while l < r:
        mid = (l+r)//2
        if nums[mid] > nums[mid+1]:
            r = mid
        else:
            l = mid+1
            
    return l
```

## 222. Count Complete Tree Nodes

Given a **complete** binary tree, count the number of nodes.

Can you solve in O(d) time

```python
"""
The node number in last level: 1 ~ 2^d-1
Use 2 binary search, first search if idx exist in last level, second in 'exist function'
Time O(2d)

1. find depth of root
2. return 1 if d == 0
3. Use 'exist' function to find if left idx exist
4. Implement exist(idx, root, d)

"""

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root: return 0
        d = self.getDepth(root)
        if d == 0: return 1
        
        left, right = 1, 2**d
        
        while left < right:
            mid = (left + right)//2
            if self.exist(mid, root, d):
                left = mid + 1
            else:
                right = mid
        return (2**d-1) + left
        

    def getDepth(self, node):
        d = 0
        while node.left:
            node = node.left
            d += 1
        return d
    
    def exist(self, idx, node, d):
        left, right = 0, 2**d-1
        
        for _ in range(d):
            mid = (left + right)//2
            if idx <= mid:
                node = node.left
                right = mid
            else:
                node = node.right
                left = mid
        return node is not None
    
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://netjimmy.gitbook.io/code-interview-note/binary_search/save-the-half-which-has-result.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
