美文网首页工作生活
222. Count Complete Tree Nodes [

222. Count Complete Tree Nodes [

作者: 一个想当大佬的菜鸡 | 来源:发表于2019-07-04 13:42 被阅读0次

222. Count Complete Tree Nodes

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

相关文章

网友评论

    本文标题:222. Count Complete Tree Nodes [

    本文链接:https://www.haomeiwen.com/subject/lmblhctx.html