Leetcode 938.二叉搜索树的范围和

Leetcode 938.二叉搜索树的范围和

原题戳这里

题解:

  • 这里是用了dfs搜索
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int dfs(TreeNode *r, int low, int high){
        int res = 0;
        if (r->val >= low && r->val <= high) res = r->val;

        if (r->left != NULL) res += dfs(r->left, low, high);
        if (r->right != NULL) res += dfs(r->right, low, high);
        return res;
    }

    int rangeSumBST(TreeNode* root, int low, int high) {
        int res = 0;
        res = dfs(root, low, high);
        return res;
    }
};
上一篇:xml的解构与组装


下一篇:java学习笔记--1_常见输入输出语句熟悉篇章