【发布时间】:2021-03-24 22:34:33
【问题描述】:
我正在练习一些 Leetcode 树/递归问题。我仍然没有掌握他们的窍门。问题是给定二叉树的根,返回子树的数量,其中所有节点具有相同的值。 https://leetcode.com/explore/learn/card/data-structure-tree/17/solve-problems-recursively/538/.我的解决方案返回的子树比正确答案少。我想不通。谢谢。
class Solution:
def countUnivalSubtrees(self, root: TreeNode) -> int:
if root is None:
return 0
self.count = 0
self.isUnivalSubtree(root)
return self.count
def isUnivalSubtree(self, root:TreeNode) -> bool:
if (root.left is None) and (root.right is None):
self.count += 1
return True
if (root.left is None) and (root.right is not None):
if self.isUnivalSubtree(root.right) and (root.val == root.right.val):
self.count += 1
return True
else:
return False
if (root.right is None) and (root.left is not None):
if self.isUnivalSubtree(root.left) and (root.val == root.left.val):
self.count += 1
return True
else:
return False
if (root.right is not None) and (root.left is not None):
if self.isUnivalSubtree(root.left) and self.isUnivalSubtree(root.right) and (root.val == root.left.val) and (root.val == root.right.val):
self.count += 1
return True
else:
return False
【问题讨论】:
-
这个问题被付费墙阻止了。如果您可以分享一些输入和预期输出,那就太好了。