【树】938. 二叉搜索树的范围和

题目:

解答:

方法一:深度优先搜索

我们对树进行深度优先搜索,对于当前节点 node,如果 node.val 小于等于 L,那么只需要继续搜索它的右子树;如果 node.val 大于等于 R,那么只需要继续搜索它的左子树;如果 node.val在区间 (L, R) 中,则需要搜索它的所有子树。

我们在代码中用递归和迭代的方法分别实现了深度优先搜索。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int ans;
13     int rangeSumBST(TreeNode* root, int L, int R) 
14     {
15         ans = 0;
16         dfs(root, L, R);
17 
18         return ans;
19     }
20 
21     void dfs(TreeNode *root, int L, int R) 
22     {
23         if (NULL != root) 
24         {
25             if (L <= root->val && root->val <= R)
26             {
27                 ans += root->val;
28             }
29             if (L < root->val)
30             {
31                 dfs(root->left, L, R);
32             }
33             if (root->val < R)
34             {
35                 dfs(root->right, L, R);
36             }
37         }
38     }
39 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12822145.html