【LeetCode】663.均匀树划分

663.均匀树划分

知识点:二叉树;递归

题目描述

给定一棵二叉树,允许剪断一个树枝,这样能生成两棵树,问是否存在一条树枝,使得其被剪断后产生的两棵树的节点和相等。

示例
样例 1:
输入:     
    5
   / \
  10 10
    /  \
   2   3
输出: True
解释: 
    5
   / 
  10
      
和: 15

   10
  /  \
 2    3

和: 15
 

样例 2:
输入:     
    1
   / \
  2  10
    /  \
   2   20
输出: False
解释: 无法通过移除一条树边将这棵树划分成结点之和相等的两棵子树。
 

解法一:二叉树遍历

拆分两棵树,然后让两棵树的节点值之和相等,所以可以直接求整棵树的节点值,然后看是否有哪颗树的节点值之和为整个和的一半。
所以可以遍历二叉树,用一个数组记录每个子树的节点值之和,然后再看数组里是否有其一半就行了

from collections import deque
class TreeNode:  # 树节点的结构
    def __init__(self, data):
        self.val = data
        self.leftchild = None
        self.rightchild = None

class Solution:
    def __init__(self):
        self.record_list = []  # 记录每个子树的和
    #这个方法的意思是if题目中给的并不是树的结构,而是一个数组,也就是树的层序遍历,那要能够根据层序遍历构建树
    def create_tree(self, nodelist):  # 根据层序遍历构建树
        if nodelist[0] == -1:
            return -1
        queue = deque()
        index = 1
        head = TreeNode(nodelist[0])
        queue.append(head)
        while queue:
            cur_node = nodelist[index]
            node = queue.popleft()
            if cur_node == -1:
                node.leftchild = None
            else:
                node.leftchild = TreeNode(cur_node)
                queue.append(node.leftchild)
            index += 1
            if index == len(nodelist): 
                return head
            cur_node = nodelist[index]
            if cur_node == -1:
                node.rightchild = None
            else:
                node.rightchild = TreeNode(cur_node)
                queue.append(node.rightchild)
            index += 1
            if index == len(nodelist):
                return head
        return head

    def sum(self, head_node):
        ans = head_node.val
        if head_node.leftchild != None:
            ans += sum(head_node.left)
        if head_node.rightchild != None:
            ans += sum(head_node.rightchild)
        self.record_list.append(ans)  #记录每个子树的和
        return ans
    
    def checkequaltree(self, root):
        allsum = sum(root)
        if allsum % 2 != 0:
            return False
        half_sum = allsum // 2
        self.record_list.pop(len(self.record_list)-1)  #求的是子树,去除掉root
        return half_sum in self.record_list
posted @ 2022-04-08 11:04  Curryxin  阅读(196)  评论(0编辑  收藏  举报
Live2D