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;
    }
}
相关推荐
H.莓飛2 小时前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
饮水桶_T7 小时前
Python 面向对象(十七)|继承、封装、多态 笔记
数据结构·笔记·算法
风落青芜13 小时前
链式二叉树的实现与基本操作
c语言·开发语言·数据结构·算法
wo_jack15 小时前
C++ 入门笔记(十八):list 进阶 —— const 迭代器、operator-> 与 clear 的坑
数据结构·c++·面试·stl·list
ashiho1 天前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口
xys_6781 天前
JavaSE通关手册:数组
数据结构
风落青芜1 天前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
老师我太想进步了20263 天前
【数据结构-8】栈的实现
c语言·数据结构·算法
【心态好不摆烂】4 天前
数据结构基础精讲3
数据结构·算法
岑梓铭4 天前
《考研408数据结构》第七章(B树 和 B+树)复习笔记
数据结构·笔记·b树·考研·408