222. 完全二叉树的节点个数

Q:

给出一个完全二叉树,求出该树的节点个数。

说明:

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例:

输入:
1
/
2 3
/ \ /
4 5 6

输出: 6

A:

1.土方法:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        _maxdepth,final_cnt=0,0
        flag=1
        def dfs(node,curdepth):
            nonlocal _maxdepth,final_cnt,flag
            if not flag or not node:
                return
            _maxdepth=max(_maxdepth,curdepth)
            if node and not node.left and not node.right and curdepth==_maxdepth:
                final_cnt+=1
                return
            if node and not node.left and not node.right and curdepth==_maxdepth-1:
                flag=0
                return
            if node.left:
                dfs(node.left,curdepth+1)
            if node.right:
                dfs(node.right,curdepth+1)
        dfs(root,0)
        return 2**_maxdepth-1+final_cnt

2.不那么土的:

#
# @lc app=leetcode.cn id=222 lang=python3
#
# [222] 完全二叉树的节点个数
#
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        def depth(node):
            depth=0
            while node and node.left:
                node=node.left
                depth+=1
            return depth
        if not root:
            return 0
        le=depth(root.left) 
        ri=depth(root.right)
        if le==ri and root.left:
            return (1<<(le+1))+self.countNodes(root.right)
        elif root.right:
            return (1<<(ri+1))+self.countNodes(root.left)
        return 1
posted @ 2019-09-03 21:28  NeoZy  阅读(109)  评论(0编辑  收藏  举报