563. 二叉树的坡度 ( dfs 递归 )

LeetCode:563. 二叉树的坡度

在这里插入图片描述

题目概述: 左右节点之间的差值的绝对值之和

dfs 递归


AC Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    

    int ans = 0;
    public int findTilt(TreeNode root) {
    
    
        if(root == null) return ans;
        dfs(root);
        return ans;
    }

    public int dfs(TreeNode node){
    
    
        if(node == null) return 0;

        int a = dfs(node.left);
        int b = dfs(node.right);
		
		// 结果
        ans += Math.abs(a - b);
        
        // 返回左右子树的节点和
        return a + b + node.val;
    }
}



猜你喜欢

转载自blog.csdn.net/qq_43765535/article/details/112976584