forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0222.py
34 lines (29 loc) · 741 Bytes
/
0222.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def height(t):
h = -1
while t:
h += 1
t = t.left
return h
h = height(root)
nodes = 0
while root:
if height(root.right) == h - 1: #满二叉树
nodes += 2**h
root = root.right
else:
nodes += 2**(h - 1)
root = root.left
h -= 1
return nodes