递归与二叉树_leetcode222

此博客内容为转载,原文链接为https://www.cnblogs.com/lux-ace/p/10546791.html ,标签涉及数据结构与算法。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution1(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0

return self.countNodes(root.left)+self.countNodes(root.right)+1

# https: // segmentfault.com / a / 1190000011040217
# https://blog.youkuaiyun.com/qq_17550379/article/details/82052746

# 如果右子树的高度等于整棵二叉树的高度-1的话,那么左子树一定是一棵满二叉树,
# 这个时候我们就很容易的计算出总结点数nodes=2**(h)-1 + 1 +右子树节点数(这里的+1表示root节点)。
# 如果右子树的高度不等于整棵二叉树的高度-1的话,那么左子树不一定是一棵满二叉树,但是有一点可以确定,
# 右子树一定是一棵满二叉树,这个时候我们就很容易的计算出总结点数nodes=2**(h-1)-1 + 1 +左子树节点数(这里的+1表示root节点)。
# 根据这个思路我们只要不断循环下去直到root==None结束。




class Solution2(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def height(t):
h = -1
while t:
h += 1
t = t.left
return t

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



class Solution3(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""

def getHeight(node):
height = 0
tempNode = node

while tempNode:
height += 1
tempNode = tempNode.left
return height

nodes = 0

tempRoot = root

while tempRoot:

height = getHeight(tempRoot)

rightHeight = getHeight(tempRoot.right)


if rightHeight == height-1:
nodes += 2 ** (height-1)
tempRoot = tempRoot.right

else:
nodes += 2 ** (height-2)
tempRoot = tempRoot.left

return nodes

转载于:https://www.cnblogs.com/lux-ace/p/10546791.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值