563. 二叉树的坡度

563. 二叉树的坡度

原题

java 复制代码
/**
 * 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 res = 0;
    public int findTilt(TreeNode root) {
        if(root==null){
            return 0;
        }
        dfs(root);
        return res;
    }
    public int dfs(TreeNode root){
        if(root==null){
            return 0;
        }
        //左子树遍历递归
        int left = dfs(root.left);
        //右子树遍历递归
        int right = dfs(root.right);
        //求累计坡度
        res += Math.abs(left-right);
        //计算当前结点和其子树的总值
        return root.val+left+right;
    }
}
相关推荐
鱼跃鹰飞22 分钟前
Leetcode会员尊享100题:270.最接近的二叉树值
数据结构·算法·leetcode
Queenie_Charlie28 分钟前
小陶的疑惑2
数据结构·c++·树状数组
Queenie_Charlie2 小时前
小陶与杠铃片
数据结构·c++·树状数组
云深处@3 小时前
【C++】AVL树
数据结构
Yvonne爱编码3 小时前
JAVA数据结构 DAY4-ArrayList
java·开发语言·数据结构
czxyvX5 小时前
016-二叉搜索树(C++实现)
开发语言·数据结构·c++
执着2595 小时前
力扣hot100 - 94、二叉树的中序遍历
数据结构·算法·leetcode
-dzk-5 小时前
【代码随想录】LC 707.设计链表
数据结构·c++·算法·链表
you-_ling6 小时前
数据结构:3.栈和队列
数据结构
梵刹古音7 小时前
【C语言】 递归函数
c语言·数据结构·算法