【二叉树】刷题 / 复习 记录
二叉树的前/中/后序遍历
https://leetcode.cn/problems/binary-tree-preorder-traversal/
前序遍历:根 -> 左 -> 右
中序遍历:左 -> 根 -> 右
后序遍历:左 -> 右 -> 根
前:
/**
* 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:
void dfs(TreeNode *root, vector<int> &ans) {
if(root == NULL) return;
ans.push_back(root->val);
dfs(root->left, ans);
dfs(root->right, ans);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
dfs(root, ans);
return ans;
}
};
中:
void dfs(TreeNode *root, vector<int> &ans) {
if(root == NULL) return;
dfs(root->left, ans);
ans.push_back(root->val);
dfs(root->right, ans);
}
后:
void dfs(TreeNode *root, vector<int> &ans) {
if(root == NULL) return;
dfs(root->left, ans);
dfs(root->right, ans);
ans.push_back(root->val);
}
653. Two Sum IV - Input is a BST
/**
* 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:
map<int, int> mp;
bool findTarget(TreeNode* root, int k) {
if(root == NULL) return 0;
mp[root->val]++;
if(mp[k - root->val]) {
if(k == 2 * root->val && mp[root->val] >= 2 || k != 2 * root->val) return 1;
}
bool f1 = 0, f2 = 0;
if(root->left) {
f1 = findTarget(root->left, k);
}
if(root->right) {
f2 = findTarget(root->right, k);
}
return f1 || f2;
}
};

浙公网安备 33010602011771号