题目链接:938. 二叉搜索树的范围和
二叉搜索树的特点:当前节点的值比左子树大,比右子树小。
每遍历到一个节点,判断它的值是否在规定的范围([low, high])内,
如果是,则范围递归左右子树节点之和;
如果 < low,则对当前节点的右子树进行递归;
如果 > high,则对当前节点的左子树进行递归。
/**
* 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 rangeSumBST(TreeNode* root, int low, int high) {
if (root == nullptr) {
return 0;
}
if (root->val >= low && root->val <= high) {
return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
} else if (root->val > high) {
return rangeSumBST(root->left, low, high);
} else { // root->val < low
return rangeSumBST(root->right, low, high);
}
}
};
题目链接:剑指 Offer 27. 二叉树的镜像
每到一个新的节点,交换它的左右孩子的指向,之后继续递归。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void traversal(TreeNode *root) {
if (root != NULL) {
TreeNode *temp = root->right;
root->right = root->left;
root->left = temp;
traversal(root->left);
traversal(root->right);
}
}
TreeNode* mirrorTree(TreeNode* root) {
traversal(root);
return root;
}
};