226.Invert The Binary Tree
/**
* 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 reverseTree(TreeNode *node)
{
TreeNode *tmp_ = node->right;
node->right = node->left;
node->left = tmp_;
if(nullptr != node->left) reverseTree(node->left);
if(nullptr != node->right) reverseTree(node->right);
}
TreeNode* invertTree(TreeNode* root) {
if(nullptr == root)
return root;
reverseTree(root);
return root;
}
};
669 Trim The Bianry Tree
/**
* 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:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if(nullptr == root)
return root;
if(root->val > R)
return trimBST(root->left, L, R);
if(root->val < L)
return trimBST(root->right, L, R);
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
};
100. Is Same Binary Tree
/**
* 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:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(nullptr == p && nullptr == q)
return true;
if((nullptr == p && nullptr != q) ||
(nullptr == q && nullptr != p))
return false;
if(p->val != q->val)
return false;
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
501.二叉树中的众数
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void middleSearch(TreeNode* root, vector<int>& out, int& preVal, int& preCount, int& count)
{
if (nullptr == root) {
return;
}
middleSearch(root->left, out, preVal, preCount, count);
// visit
if (count <= 0) {
preVal = root->val;
count = 1;
}
else {
if (root->val != preVal) {
if (count > preCount) {
out.clear();
out.push_back(preVal);
preCount = count;
}
else if (count == preCount) {
out.push_back(preVal);
}
preVal = root->val;
count = 1;
}
else
count++;
}
middleSearch(root->right, out, preVal, preCount, count);
}
vector<int> findMode(TreeNode* root) {
vector<int> out_;
int preVal_ = 0;
int preCount_ = 0, count_ = 0;
if (nullptr == root)
return out_;
middleSearch(root, out_, preVal_, preCount_, count_);
// s收尾处理
if (count_ > preCount_) {
out_.clear();
out_.push_back(preVal_);
}
else if (count_ == preCount_) {
out_.push_back(preVal_);
}
return out_;
}

本文深入探讨了二叉树的多种操作与算法实现,包括树的翻转、修剪、比较以及查找二叉树中的众数。通过具体的代码示例,详细解释了如何使用递归方法来解决这些树形结构的问题。
1239

被折叠的 条评论
为什么被折叠?



