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;
    }
}
相关推荐
来一碗刘肉面5 小时前
栈的应用(表达式求值)
数据结构·算法
yuannl108 小时前
图的深度优先遍历DFS
数据结构
青山木11 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
不会就选b11 小时前
算法日常・每日刷题--<归并排序>1
数据结构·算法
危桥带雨12 小时前
排序算法(快排、归并、计数、基数排序)
数据结构·算法·排序算法
zephyr0512 小时前
数据结构-并查集
数据结构
稚南城才子,乌衣巷风流13 小时前
DFS序详解:原理、应用与实现
算法·深度优先·图论
稚南城才子,乌衣巷风流13 小时前
动态树(Dynamic Tree)数据结构详解
数据结构·算法
zander25813 小时前
114. 二叉树展开为链表
数据结构·链表·深度优先
小肝一下14 小时前
3. 单链表
c语言·数据结构·c++·算法·leetcode·链表·dijkstra