The maximum average of 1120. subtree

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
  double res = 0;

    public double maximumAverageSubtree(TreeNode root) {
        solve(root);
        return res;
    }

    public int[] solve(TreeNode root) {                                                    //少用静态的 不然会保存上次运行的结果
        int arr[] = new int[2];
        arr[0] = 1;
        arr[1] = root.val;
        if (root.left != null) {
            int [] temp = solve(root.left);                                             //用一个temp保存数组 因为用solve(root.left)[0] 会超时 ~~想无
            arr[1] += temp[1];
            arr[0] += temp[0];

        }
        if (root.right != null) {
            int [] temp = solve(root.right);
            arr[1] += temp[1];
            arr[0] += temp[0];

        }
        this.res = Math.max(this.res, arr[1] * 1.0 / arr[0]);
        return arr;

    }
}

Problem Description: Brush title in leetcode time, and sometimes there will be, when the test is not wrong, but the author would be wrong. This is a headache
problem I encountered several times, slowly found the truth. For everyone to share,
1. Do not use global variables as much as possible, this has been explained leetcode
2. If you are java, as well as the use of global variables. Remember never to use static modification, do not appear static in your code,  
3. The code you write is really a problem, you then take a look at it.
4. temporarily only found these problems, if discovered late, will continue to add.

Guess you like

Origin www.cnblogs.com/cznczai/p/11183119.html