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;
    }
}
相关推荐
ゞ 正在缓冲99%…4 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
努力写代码的熊大5 小时前
单链表和双向链表
数据结构·链表
Orlando cron6 小时前
数据结构入门:链表
数据结构·算法·链表
许愿与你永世安宁11 小时前
力扣343 整数拆分
数据结构·算法·leetcode
Heartoxx12 小时前
c语言-指针(数组)练习2
c语言·数据结构·算法
杰克尼13 小时前
1. 两数之和 (leetcode)
数据结构·算法·leetcode
学不动CV了1 天前
数据结构---线性表理解(一)
数据结构
ysa0510301 天前
数论基础知识和模板
数据结构·c++·笔记·算法
今天背单词了吗9801 天前
算法学习笔记:7.Dijkstra 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·开发语言·数据结构·笔记·算法
气质、小青年!1 天前
【排序算法】
c语言·数据结构