My code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private class Result {
int size;
int min;
int max;
Result(int size, int min, int max) {
this.size = size;
this.min = min;
this.max = max;
}
}
private int maxNum = 0;
public int largestBSTSubtree(TreeNode root) {
if (root == null) {
return 0;
}
helper(root);
return maxNum;
}
private Result helper(TreeNode root) {
if (root == null) {
return new Result(0, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
Result left = helper(root.left);
Result right = helper(root.right);
if (left.size == -1 || right.size == -1 || root.val < left.max || root.val > right.min) {
return new Result(-1, 0, 0);
}
int size = left.size + 1 + right.size;
maxNum = Math.max(maxNum, size);
int min = (left.min == Integer.MAX_VALUE ? root.val : left.min);
int max = (right.max == Integer.MIN_VALUE ? root.val : right.max);
return new Result(size, min, max);
}
}
reference:
https://discuss.leetcode.com/topic/36995/share-my-o-n-java-code-with-brief-explanation-and-comments
這道題目并沒能自己寫出來。。。
類似的想法是有的。就是從底到頂,backtracking
當時我怎么想的呢?然后放棄了。
我想的是返回一個二維數(shù)組,第一位表示size,第二位表示這棵樹最大值。
后來發(fā)現(xiàn)對于右子樹來說,我們還需要知道最小值。然后我就懶得繼續(xù)想下去了。
后來看了答案,發(fā)現(xiàn)返回一個類,類里面也是三個值:
size
min
max
其實當時自己的想法就差一點了。
時間復雜度是 O(n)
然后這種自定義類,返回一個類的做法,的確比我返回一個三位數(shù)組好多了。
另外,當root == null的時候,處理的辦法也是亮點。
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
所以如果是左子樹為空,那么我們需要看他的最大值是否小于root.val
的確是小于的,沒問題。
如果右子樹為空,那么我們需要看他的最小值是否大于root.val,
的確是大于的,沒問題。
題目里說,如果是 top - down的recursion,時間復雜度是:
O(n log n) 一直沒想明白。
Anyway, Good luck, Richardo! -- 09/07/2016