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;
    }
}
相关推荐
w_zero_one42 分钟前
算法--构造
java·数据结构·算法
lisw054 小时前
互联网上的数据结构可视化!
数据结构·信息可视化
老师我太想进步了202610 小时前
【数据结构-1】例解算法复杂度
数据结构·算法
YSL07012411 小时前
一文通关-----排序
数据结构·算法
夜不会漫长1 天前
C++:红黑树
数据结构·算法
冻柠檬飞冰走茶1 天前
PTA刷题集之Airline Routes(C语言实现)
c语言·开发语言·数据结构·算法
736c1 天前
固件开发岗算法
数据结构·算法
冻柠檬飞冰走茶1 天前
PTA刷题集之Battle Over Cities - Hard Version(C语言实现)
c语言·开发语言·数据结构·算法
PaperAccept1 天前
【研知有术论文发表】材料科学一区期刊,影响因子30+的纳米科技SCI,审稿严格但有效率
大数据·数据结构·科技·量子计算
Tairitsu_H1 天前
[C++高阶数据结构·图论下] 最短路径:为什么“挑最小的”一定正确?
数据结构·c++·图论