题目链接:https://leetcode-cn.com/problems/count-complete-tree-nodes/
难度:中等
描述:
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含个节点。
题解
直接遍历二叉树的所有结点
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclass Solution:def countNodes(self, root: TreeNode) -> int:ret = []def dfs(root):ret.append(0)if root.left:dfs(root.left)if root.right:dfs(root.right)if root is None:return 0dfs(root)return len(ret)# 还可以优化
比较左右子树的高度
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclass Solution:def countNodes(self, root: TreeNode) -> int:def get_height(root):height = 0while root:height += 1root = root.leftreturn heightret = 0while root:left_height = get_height(root.left)right_height = get_height(root.right)# 高度相同说明左子树是满的,加上左子树的节点数目再加1(root节点)if left_height == right_height:ret += 2 ** left_heightroot = root.rightelse: # 说明右子树是满的,加上右子树的节点数目再加1(root节点)ret += 2 ** right_heightroot = root.leftreturn ret
