/**
* 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 getMinimumDifference(TreeNode* root) {
stack<TreeNode*>s;
int min=INT_MAX;
int pre=INT_MAX;
s.push(root);
while(!s.empty()){
TreeNode* node=s.top();
s.pop();
if(node==NULL){
node=s.top();
s.pop();
if(abs(pre-node->val)<min) min=abs(pre-node->val);
pre=node->val;
}else{
if(node->right!=NULL) s.push(node->right);
s.push(node);
s.push(NULL);
if(node->left!=NULL) s.push(node->left);
}
}
return min;
}
};
也是利用搜索树中序遍历递增的特性。
/**
* 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:
vector<int> findMode(TreeNode* root) {
stack<TreeNode*>s;
int max=0,num=1;
int pre=INT_MAX;
vector<int> result;
s.push(root);
while(!s.empty()){
TreeNode* node=s.top();
s.pop();
if(node==NULL){
node=s.top();
s.pop();
if(max==0){
pre=node->val;
max=1;
}else{
if(node->val==pre){
num++;
}else{
if(num==max){
result.push_back(pre);
}else if(num>max){
result={pre};
max=num;
}
num=1;
pre=node->val;
}
}
}else{
if(node->right!=NULL) s.push(node->right);
s.push(node);
s.push(NULL);
if(node->left!=NULL) s.push(node->left);
}
}
if(num==max){
result.push_back(pre);
}else if(num>max){
result={pre};
}
return result;
}
};
同样是利用单调性质。
/**
* 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==p||root==q||root==NULL) return root;
TreeNode* l=lowestCommonAncestor(root->left,p,q);
TreeNode* r=lowestCommonAncestor(root->right,p,q);
if(l!=NULL&&r!=NULL) return root;
if(l!=NULL) return l;
if(r!=NULL) return r;
return NULL;
}
};
因为后序遍历自底向上的遍历顺序,递归过程中,在root节点是p或q的祖先节点时,l与r不会同时为空,而在root的l与r均不为空时,代表p与q分别在root的两侧子树中,代表root为祖先节点,则返回root,索引在递归结束后,返回的一定时最早的祖先节点。