[LeetCode] 563. The slope of a binary tree (recursive realization)

Given a binary tree, calculate the slope of the entire tree.

The slope of a node of a tree is defined as the absolute value of the difference between the sum of the nodes of the left subtree and the sum of the nodes of the right subtree of the node. The slope of the empty node is 0.

The slope of the entire tree is the sum of the slopes of all its nodes.

Example:

Input:
1
/ \
2 3

Output: 1
Explanation:
The slope of the node 2: 0
The slope of the node 3: 0
The slope of the node 1: |2-3| = 1
The slope of the tree: 0 + 0 + 1 = 1

note:

  • The sum of the nodes of any subtree will not exceed the range of 32-bit integers.
  • The value of the slope will not exceed the range of a 32-bit integer.
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    int ans = 0;
    public int findTilt(TreeNode root) {
    
    
        if(root!=null){
    
    
            sumTilt(root);
        }
        return ans;
    }
    
    public int sumTilt(TreeNode root){
    
    
        if(root!=null){
    
    
            int leftValue = sumTilt(root.left);     //递归左子树
            int rightValue = sumTilt(root.right);   //递归右子树
            ans += Math.abs(leftValue - rightValue);    //计算并添加 当前结点梯度
            return root.val + leftValue + rightValue;   //向父母结点返回 左/右 结点之和
        }
        return 0;
    }
}

Guess you like

Origin blog.csdn.net/weixin_40849588/article/details/89409092