LeetCode222-完全二叉树的节点个数
作者:互联网
原题链接:https://leetcode-cn.com/problems/count-complete-tree-nodes/
解题思路:树形DP
代码:
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, val=0, left=None, right=None): 4 # self.val = val 5 # self.left = left 6 # self.right = right 7 class Solution: 8 def countNodes(self, root: TreeNode) -> int: 9 if not root: 10 return 0 11 return self.process(root) 12 13 def process(self, x: TreeNode) -> int: 14 if not x: 15 return 0 16 left_cnt = self.process(x.left) 17 right_cnt = self.process(x.right) 18 return left_cnt + right_cnt + 1
相关问题:
如何判断一个树为完全二叉树
解题思路:树形DP
代码:
1 class TreeNode: 2 def __init__(self, val=0, left=None, right=None): 3 self.val = val 4 self.left = left 5 self.right = right 6 7 class ReturnData: 8 def __init__(self, height, nodes): 9 self.height = height 10 self.nodes = nodes 11 12 def process(x: TreeNode) -> ReturnData: 13 if not x: 14 return ReturnData(0, 0) 15 leftData = process(x.left) 16 rightData = process(x.right) 17 18 height = max(leftData.height, rightData.height) + 1 19 nodes = leftData.nodes + rightData.nodes + 1 20 return ReturnData(height, nodes) 21 22 def is_cbt(root: TreeNode) -> bool: 23 res = process(root) 24 if res.nodes == 1 >> res.height - 1: 25 return True 26 return False
标签:right,return,LeetCode222,self,height,二叉树,nodes,节点,left 来源: https://www.cnblogs.com/BigPeng965/p/15799803.html