2021.11.18 - 154.二叉树的坡度

1. 题目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2. 思路

(1) 递归

  • 利用全局变量记录坡度之和,利用递归函数返回当前结点的坡度即可。

3. 代码

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

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 {
    
    
    private int res;

    public int findTilt(TreeNode root) {
    
    
        recur(root);
        return res;
    }

    private int recur(TreeNode root) {
    
    
        if (root == null) {
    
    
            return 0;
        }
        int left = recur(root.left);
        int right = recur(root.right);
        res += Math.abs(left - right);
        return left + right + root.val;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/121405240