zoukankan      html  css  js  c++  java
  • 递归与二叉树_leetcode222

    # 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.csdn.net/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
  • 相关阅读:
    CentOS7安装mysql
    strusts2的开发包
    CentOS7配置mavne国内镜像
    卸载linux自带的jdk
    Centos7安装nodejs
    redis启动方式
    bash学习笔记——Shell变量
    bash学习笔记——bash是什么
    教育管理系统——android家长客户端
    php入门学习——php与jsp对比
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546791.html
Copyright © 2011-2022 走看看