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;
    }
}
相关推荐
Amor风信子20 分钟前
华为OD机试真题---跳房子II
java·数据结构·算法
Ljubim.te1 小时前
软件设计师——数据结构
数据结构·笔记
liuyang-neu2 小时前
力扣 简单 110.平衡二叉树
java·算法·leetcode·深度优先
_GR2 小时前
每日OJ题_牛客_牛牛冲钻五_模拟_C++_Java
java·数据结构·c++·算法·动态规划
无限大.3 小时前
c语言实例
c语言·数据结构·算法
@haihi3 小时前
冒泡排序,插入排序,快速排序,选择排序
数据结构·算法·排序算法
丢掉幻想准备斗争3 小时前
数据结构(栈和队列的实现)
数据结构
zengy54 小时前
Effective C++中文版学习记录(三)
数据结构·c++·学习·stl
&梧桐树夏7 小时前
【算法系列-链表】删除链表的倒数第N个结点
数据结构·算法·链表
QuantumStack7 小时前
【C++ 真题】B2037 奇偶数判断
数据结构·c++·算法