【树】C000_二叉搜索树的范围和(dfs 递归 | 非递归)

一、题目描述

Given the root node of a binary search tree, return the sum of values of 
all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.

Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32

二、题解

方法一:dfs 递归

思路

题意:求出所有大于 L 且小于 R 的值的和

  • 当前节点为 null 时 dfs 返回。
  • 当前节点 X < L 时则递归右子树。
  • 当前节点 X > R 时则递归左子树。
  • 当前节点大于 L 且小于 R 时,可累加其 val 到 sum 中
    在这里插入图片描述
int sum = 0;
public int rangeSumBST(TreeNode root, int L, int R) {
  dfs(root, L, R);
  return sum;
}

private void dfs(TreeNode node, int L, int R) {
  if (node == null) {
    return;
  }
  if (L <= node.val && node.val <= R) {
    sum += node.val;
    dfs(node.left, L, R);
    dfs(node.right, L, R);
    return;
  }
  if (node.val < L) {
    dfs(node.right, L, R);
    return;
  }
  if (node.val > R)
    dfs(node.left, L, R);
}

复杂度分析

  • 时间复杂度: O ( N ) O(N) ,其中 N 是树中的节点数目。
  • 空间复杂度: O ( H ) O(H) ,H 为树的高度。

方法二:非递归 dfs

private void dfs_2(TreeNode node, int L, int R) {
  stack = new Stack<>();
  stack.push(node);
  while (!stack.isEmpty()) {
    TreeNode T = stack.pop();
    if (T == null)
      continue;
    if (L <= T.val && T.val <= R)
      sum += T.val;
    if (T.val > L)
      stack.push(T.left);
    if (T.val < R)
      stack.push(T.right);
  }
}

复杂度分析

  • 时间复杂度: O ( N ) O(N) ,其中 N 是树中的节点数目。
  • 空间复杂度: O ( H ) O(H) ,H 为树的高度。
发布了419 篇原创文章 · 获赞 94 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/104483492