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 天前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
什巳1 天前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
想做小南娘,发现自己是女生喵1 天前
第 2 章 顺序表和 vector
java·数据结构·算法
en.en..1 天前
冒泡排序与选择排序完整对比解析
开发语言·数据结构·算法·c#·排序算法
Jayden_Ruan1 天前
C++组合的输出
c++·算法·深度优先
什巳1 天前
JAVA练习312- 二叉搜索树中第 K 小的元素
java·数据结构·算法·leetcode
LJHclasstore_luo1 天前
【C++题解】118875.最大宝藏区
数据结构·c++·算法
罗超驿1 天前
9.优先级队列与堆:从底层原理到实战应用的完整指南
数据结构·算法
牧以南歌〆1 天前
数据结构<三>单循环链表
c语言·数据结构·算法·链表
Java技术实战2 天前
一文通解:数据结构之 栈
java·jvm·数据结构·