花重金 斥巨资买了 leetcode premium,决定要开始刷题!
第938题 Range Sum of BST 思路是遍历树,找到规定范围的所有节点的值总和。
1)这是我自己的写法:1ms 46.7MB 比官方非回归的快
/**
* 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 {
public int rangeSumBST(TreeNode root, int L, int R) {
TreeNode node = root;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
int val = node.val;
int ans =0;
while(node!=null || !queue.isEmpty()){
if(node==null) node=queue.poll();
val = node.val;
if(val<low) {
if(node.right==null) node=queue.poll();
else{
node = node.right;
}
}
else if(val>high){
if(node.left==null) node=queue.poll();
else{
node = node.left;
}
}
// fall on the range
else{
ans += node.val;
if(node.right!=null) queue.add(node.right);
node = node.left;
}
}
return ans;
}
}
2) 这是官方给的 回归大法 0ms KO。
class Solution {
int ans;
public int rangeSumBST(TreeNode root, int L, int R) {
ans = 0;
dfs(root, L, R);
return ans;
}
public void dfs(TreeNode node, int L, int R) {
if (node != null) {
if (L <= node.val && node.val <= R)
ans += node.val;
if (L < node.val)
dfs(node.left, L, R);
if (node.val < R)
dfs(node.right, L, R);
}
}
}
总结:善用回归~