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;
    }
}
相关推荐
浅念-1 小时前
链表经典面试题目
c语言·数据结构·经验分享·笔记·学习·算法
czwxkn2 小时前
数据结构-线性表
数据结构
tobias.b2 小时前
408真题解析-2010-1-数据结构-栈基础操作
数据结构·408真题解析
菜鸟233号2 小时前
力扣213 打家劫舍II java实现
java·数据结构·算法·leetcode
方便面不加香菜3 小时前
数据结构--栈和队列
c语言·数据结构
Pluchon3 小时前
硅基计划4.0 算法 动态规划进阶
java·数据结构·算法·动态规划
2401_841495645 小时前
【Python高级编程】单词统计与查找分析工具
数据结构·python·算法·gui·排序·单词统计·查找
Bruce_kaizy5 小时前
c++ dfs搜索算法——剪枝
c++·深度优先·剪枝
-To be number.wan6 小时前
【数据结构真题解析】哈希表高级挑战:懒惰删除、探测链断裂与查找正确性陷阱
数据结构·算法·哈希算法
Qhumaing6 小时前
数据结构——例子求算法时间复杂度&&空间复杂度
数据结构·算法