563. The slope of a binary tree (dfs recursion)

LeetCode: 563. The slope of a binary tree

Insert picture description here

Topic overview: The sum of the absolute value of the difference between the left and right nodes

dfs recursion


AC Code

/**
 * 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 ans = 0;
    public int findTilt(TreeNode root) {
    
    
        if(root == null) return ans;
        dfs(root);
        return ans;
    }

    public int dfs(TreeNode node){
    
    
        if(node == null) return 0;

        int a = dfs(node.left);
        int b = dfs(node.right);
		
		// 结果
        ans += Math.abs(a - b);
        
        // 返回左右子树的节点和
        return a + b + node.val;
    }
}



Guess you like

Origin blog.csdn.net/qq_43765535/article/details/112976584