搜索,双指针,采取两个指针遍历,采用前中右
class Solution {
private:
int result = INT_MAX;
TreeNode* pre = NULL;
void traversal(TreeNode* cur) {
if (cur == NULL) return;
traversal(cur->left); // 左
if (pre != NULL){ // 中
result = min(result, cur->val - pre->val);
}
pre = cur; // 记录前一个
traversal(cur->right); // 右
}
public:
int getMinimumDifference(TreeNode* root) {
traversal(root);
return result;
}
};
二叉树搜索树,统计众数
依旧是前序遍历,采用双指针的办法,但是要注意相同的情况,要放在前面
/**
* 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:
TreeNode* pre=NULL;
vector<int> res;
int count=0;
int maxcount=INT_MIN;
void traversal(TreeNode* cur){
if(cur==NULL) return;
traversal(cur->left);
//第一个元素
if(pre==NULL) {count=1;}
else if(pre->val==cur->val) {count++;}
else {count=1;}
if(count==maxcount){
res.push_back(cur->val);
}
if(count>maxcount){
maxcount=count;
res.clear();
res.push_back(cur->val);
}
pre=cur;
traversal(cur->right);
}
vector<int> findMode(TreeNode* root) {
traversal(root);
return res;
}
};
二叉树公共祖先,回溯算法,采用后序遍历
/**
* 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
//回溯是后序遍历,左右中
if(root==q||root==p||root==NULL) return root;
TreeNode* left=lowestCommonAncestor(root->left,p,q);
TreeNode* right=lowestCommonAncestor(root->right,p,q);
if(left==NULL&&right!=NULL) return right;
else if(left!=NULL&&right==NULL) return left;
else if(left!=NULL&&right!=NULL) return root;
else {return NULL;}
}
};