46. 两个链表的第一个公共节点
栈的方法。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1==NULL || pHead2==NULL) return NULL;
stack<ListNode*> stk1;
stack<ListNode*> stk2;
ListNode* head1=pHead1;
ListNode* head2=pHead2;
ListNode* res;
while(head1!=NULL){
stk1.push(head1);
head1=head1->next;
}
while(head2!=NULL){
stk2.push(head2);
head2=head2->next;
}
if(stk1.top()->val!=stk2.top()->val) return NULL;
while(!stk1.empty() && !stk2.empty() && stk1.top()->val==stk2.top()->val){
res=stk1.top();
stk1.pop();
stk2.pop();
}
return res;
}
};
47. 数字在排序数组中出现的次数
循环找数字,速度不稳定。
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
if(data.size()<=0 || data[0]>k || data.back()<k) return 0;
int low=0,high=data.size()-1;
while((data[low]!=k || data[high]!=k) && low<=high){
int mid=low+(high-low)/2;
if(data[mid]<k) low=mid+1;
else if(data[mid]>k) high=mid-1;
else{
if(data[mid-1]<k) low=mid;
else if(data[low]<k) low++;
if(data[mid+1]>k) high=mid;
else if(data[high]>k) high--;
}
if(low>high) return 0;
}
return high-low+1;
}
};
48. 二叉搜索树的第K个节点
事实上考查的是中序遍历的思想
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot==NULL || k==0) return NULL;
count=k;
return KthHelp(pRoot);
}
private:
int count;
TreeNode* KthHelp(TreeNode* pRoot){
TreeNode* res=NULL;
if(pRoot==NULL) return NULL;
if(pRoot->left) res=KthHelp(pRoot->left);
if(res==NULL && count==1)
res=pRoot;
else
count--;
if(res==NULL && pRoot->right) res=KthHelp(pRoot->right);
return res;
}
};
49. 二叉树的深度
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==NULL) return 0;
return DepthHelper(pRoot,0);
}
private:
int DepthHelper(TreeNode* pRoot, int depth){
if(pRoot==NULL) return depth;
depth+=1;
return max(DepthHelper(pRoot->left,depth),DepthHelper(pRoot->right,depth));
}
};
一样的思路,想想可以用更简洁的代码实现,重写了下
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==NULL) return 0;
return max(1+TreeDepth(pRoot->left),1+TreeDepth(pRoot->right));
}
};
50. 平衡二叉树
书上的方法,有点懵还。。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==NULL) return true;
int depth=0;
return Depth(pRoot,depth);
}
private:
bool Depth(TreeNode* pRoot ,int& depth){
if(pRoot==NULL){
depth = 0;
return true;
}
int left,right;
if(Depth(pRoot->left,left) && Depth(pRoot->right,right)){
if(left-right<=1 && left-right>=-1){
depth=1+(left>right?left:right);
return true;
}
}
return false;
}
};