题目描述: 给定一个二叉树,计算整个树的坡度。
一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。
整个树的坡度就是其所有节点的坡度之和。
示例:
输入: 1 / 2 3 输出:1 解释: 结点 2 的坡度: 0 结点 3 的坡度: 0 结点 1 的坡度: |2-3| = 1 树的坡度 : 0 + 0 + 1 = 1
思路: 递归 分别计算左孩子和右孩子的和 然后求其差的绝对值 最后把每个节点的差的绝对值相加
代码如下: C++:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int sum(TreeNode* root){ if(root==NULL) return 0; return root->val+sum(root->left)+sum(root->right); } int findTilt(TreeNode* root) { if(root==NULL) return 0; return abs(sum(root->left)-sum(root->right))+findTilt(root->left)+findTilt(root->right); } };python:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findTilt(self, root: TreeNode) -> int: self.res=0 def sum(root): if not root:return 0 return root.val+sum(root.left)+sum(root.right) if not root:return 0 return abs(sum(root.left)-sum(root.right))+self.findTilt(root.left)+self.findTilt(root.right)