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;
    }
}
相关推荐
yuannl102 小时前
图的存储方式
数据结构
会编程的小孩3 小时前
初识数据类型以及变量定义
数据结构·算法
梅梅绵绵冰4 小时前
数据结构-时间复杂度
数据结构·算法
cpp_25015 小时前
P6625 [省选联考 2020 B 卷] 卡牌游戏
数据结构·c++·算法·前缀和·贪心·洛谷题解·省选
起予者汝也5 小时前
Python 数据结构
开发语言·数据结构·python
Frostnova丶7 小时前
(17)LeetCode 41. 缺失的第一个正数
数据结构·算法·leetcode
程序猿乐锅8 小时前
【数据结构与算法 | 第二篇】 双链表的增删改查
数据结构
牧以南歌〆11 小时前
数据结构<一>顺序表
c语言·数据结构·算法
玖玥拾1 天前
C++ 数据结构 八大基础排序算法专题
数据结构·c++·算法·排序算法
Tim_101 天前
【C++】017、new/delete与malloc/free的区别
java·数据结构·算法