222完全二叉树的节点个数

来源:https://leetcode-cn.com/problems/count-complete-tree-nodes/

法一: 自己的代码

思路: 刚开始的方法多遍历了一行,改进后的,只需遍历到最后一行就停,这是由完全二叉树的性质决定的,注意层序遍历二叉树的时候,这里不能用栈来实现,必须用队列,才能保证每一行都是从左往右来遍历,遍历最后一行的时候才不会出错

# 执行用时 :124 ms, 在所有 python3 提交中击败了29.46% 的用户
# 内存消耗 :20 MB, 在所有 python3 提交中击败了98.68%的用户
class Solution:
    def countNodes(self, root: TreeNode) -> int:
        stack = []
        stack_next = []
        level = 0
        if root is None:
            return 0
        stack_next.append(root)
        while stack_next:
            stack = stack_next
            stack_next = []
            l = len(stack)
            # 非空的list才能pop()
            while stack:
                # 注意这里用的是队列不是栈,为的是保证每次都是从左往右遍历
                a = stack.pop(0)
                if a:
                    stack_next.append(a.right)
                    stack_next.append(a.left)
                # 一旦遇到某个节点为空了,说明到最后一行了,直接计算并返回结果
                else:
                    return int(len(stack_next)/2) + (2 ** (level-1)) - 1
            level += 1
        # 原先的代码比较耗时,最后一行可能会无效遍历,
        # return (2 ** (level-2) - 1 + int(l/2))
View Code
原文地址:https://www.cnblogs.com/xxswkl/p/12003276.html