1. 程式人生 > >563. Binary Tree Tilt

563. Binary Tree Tilt

struct who str btree diff binary ont and solution

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes‘ tilt.

Example:

Input: 
         1
       /         2     3
Output: 1
Explanation: 
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1

Note:

  1. The sum of node values in any subtree won‘t exceed the range of 32-bit integer.
  2. All the tilt values won‘t exceed the range of 32-bit integer.

求二叉樹的傾斜

樹節點的傾斜被定義為所有左子樹節點值和所有右子樹節點值的和的絕對差。零節點有傾斜0。

C++(22ms):

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public: 12 int findTilt(TreeNode* root) { 13 if (root == NULL) 14 return 0 ; 15 int res = 0 ; 16 tilt(root,res) ; 17 return res ; 18 } 19 20 int tilt(TreeNode* root , int& res) { 21 if (root == NULL) 22 return 0 ; 23 int leftSum = tilt(root->left,res) ; 24 int rightSum = tilt(root->right,res) ; 25 res += abs(leftSum-rightSum) ; 26 return leftSum + rightSum + root->val ; 27 } 28 };

563. Binary Tree Tilt