Fork me on GitHub

1120. 子树的最大平均值

/**
 * 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;

	}
}

问题说明:在leetcode上刷题的时候,有时候会出现,测试的时候没有错,但提交就错。这就很头疼了
这个问题我遇到几次,慢慢发现了其中的道理。分享给大家,
1.尽可能不要使用全局变量,这个leetcode已经说明了
2.如果你是java,同时也使用了全局变量。 记住千万不要用 static 去修饰,在你的代码中不要出现 static,  
3.你的代码写的真的有问题,你再好好看看吧。
4.暂时只发现这些问题,后期如果又发现,会继续补充。

posted @ 2019-07-14 09:16  cznczai  阅读(542)  评论(0编辑  收藏  举报