Symmetric Tree
Given a binarytree, check whether it is a mirror of itself (ie, symmetric around its center).
For example,this binary tree is symmetric:
1
/\
2 2
/ \/ \
3 44 3
But thefollowing is not:
1
/\
2 2
\ \
3 3
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return help(root->left,root->right);
}
private:
bool help(TreeNode* left,TreeNode* right){
if(left==NULL&&right==NULL) return true;
if(left==NULL||right==NULL) return false;
if(left->val!=right->val) return false;
return(help(left->right,right->left)&&help(left->left,right->right));
}
};
注:重点!!要注意返回值,if(left->val==right->val)return true; else return false;是错误的!!易犯错误!!
Balanced Binary Tree
Given a binary tree,determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as abinary tree in which the depth of the two subtrees of every node never differ by more than 1.
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root==NULL) return true;
int l=maxdep(root->left);
int r=maxdep(root->right);
if(l-r<-1||l-r>1) return false;
else returnisBalanced(root->left)&&isBalanced(root->right);
}
private:
int maxdep(TreeNode* root){
if(root==NULL) return 0;
int l=maxdep(root->left);
int r=maxdep(root->right);
return (max(l,r)+1);
}
};
注:递归的典型题
Implement Queue using Stacks
Implement thefollowing operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
class Queue {
public:
// Push element x to the back of queue.
stack<int> s1,s2;
void transfer(){
int x;
if(s2.empty())
while(!s1.empty()){
x=s1.top();
s1.pop();
s2.push(x);
}
}
void push(int x) {
s1.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
transfer();
s2.pop();
}
// Get the front element.
int peek(void) {
int x;
transfer();
x=s2.top();
return x;
}
// Return whether the queue is empty.
bool empty(void) {
if(s1.empty()&&s2.empty()) return true;
else return false;
}
};
注:考察栈和队列的基本操作!!!
Merge Two Sorted Lists
Merge two sortedlinked lists and return it as a new list. The new list should be made bysplicing together the nodes of the first two lists.
Subscribe to see which companiesasked this question
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *head=new ListNode(3);
ListNode *p=head;
while(l1&&l2){
if(l1->val<l2->val){
p->next=l1;
p=l1;
l1=l1->next;
}
else{
p->next=l2;
p=l2;
l2=l2->next;
}
}
while(l1) {
p->next=l1;
p=l1;
l1=l1->next;}
while(l2)
{p->next=l2;
p=l2;
l2=l2->next;}
head=head->next;
return head;
}
};
注:leetcode上的链表,头结点往往带有值,创立一个新的节点,使问题简化很多