Created
March 19, 2020 02:57
-
-
Save RP-3/492116d98f051ebf505f9324ae5e9547 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Definition for a binary tree node. | |
# class TreeNode: | |
# def __init__(self, x): | |
# self.val = x | |
# self.left = None | |
# self.right = None | |
# O(h^2) | |
# Tree height = h | |
# Range of possible answers, r = 2^h | |
# Complexity = h * log2(r) | |
# = h * log2(2^h) | |
# = h * h | |
# = h^2 | |
class Solution: | |
def countNodes(self, root: TreeNode) -> int: | |
if root is None: return 0 | |
h, curr = 0, root.left | |
while(curr): | |
h+=1 | |
curr = curr.left | |
result, l, r = 1, 1, pow(2, h) | |
while(l <= r): | |
mid = (l+r)//2 | |
if self.nodeExistsAt(root, mid, h): | |
result = max(result, mid) | |
l = mid+1 | |
else: | |
result = min(result, mid) | |
r = mid-1 | |
return result + (1 << h)-1 | |
def nodeExistsAt(self, root, target, maxHeight): | |
l, r, depth = 1, pow(2, maxHeight), 0 | |
while(root is not None): | |
mid = (l+r)//2 | |
if target > mid: | |
root = root.right | |
l = mid+1 | |
else: | |
root = root.left | |
r = mid-1 | |
if root is not None: depth+=1 | |
return depth == maxHeight |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment