222. Count Complete Tree Nodes
最简单的就是遍历计数,但是没有用到Complete Tree的特性,先来个递归版本
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
再来一个深度优先的循环版本吧
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
stack = []
node = root
res = 0
while node or stack:
while node:
stack.append(node)
node = node.left
res += 1
if stack != None:
node = stack.pop()
node = node.right
return res
这道题的标签是二分查找,要用到Complete Tree的性质,如果是完全二叉树,知道深度就可以得到节点数,如果不是,递归求解
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
left = self.countLeft(root)
right = self.countRight(root)
if left == right:
return (1<<left) - 1
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
def countLeft(self, root):
res = 0
while root:
root = root.left
res += 1
return res
def countRight(self, root):
res = 0
while root:
root = root.right
res += 1
return res