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;
    }
}
相关推荐
D.....l1 小时前
冒泡排序与选择排序以及单链表与双链表
数据结构·算法·排序算法
欧阳天风1 小时前
链表运用到响应式中
javascript·数据结构·链表
靠近彗星3 小时前
2.3单链表
数据结构
徐子童4 小时前
优选算法---链表
数据结构·算法·链表·面试题
CYH&JK4 小时前
数据结构---链式队列
数据结构
shan&cen5 小时前
Day02 集合 | 30. 串联所有单词的子串、146. LRU 缓存、811. 子域名访问计数
java·数据结构·算法·缓存
阿方.9185 小时前
《树与二叉树详解:概念、结构及应用》
数据结构·二叉树··知识分享
靠近彗星6 小时前
2.2顺序表
数据结构
序属秋秋秋6 小时前
《C++进阶之STL》【哈希表】
数据结构·c++·stl·哈希算法·散列表·哈希表·哈希