[剑指Offer]二叉搜索树的第k个节点
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
int index=0;
TreeNode* KthNode(TreeNode *root, int k)
{
if(root != NULL){ //中序遍历寻找第k个
TreeNode *node = KthNode((*root).left,k);
if(node != NULL)
return node;
index ++;
if(index == k)
return root;
node = KthNode((*root).right,k);
if(node != NULL)
return node;
}
return NULL;
}
};
[剑指Offer]把二叉树打印成多行
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > ans;
vector<int > tmp;
queue<TreeNode* > TreeQ1;
queue<TreeNode* > TreeQ2;
TreeQ2.push(pRoot);
while(!TreeQ2.empty()){
while(!TreeQ2.empty()){
if(TreeQ2.front() != NULL){
TreeQ1.push(TreeQ2.front());
}
TreeQ2.pop();
}
while(!TreeQ1.empty()){
TreeQ2.push(TreeQ1.front()->left);
TreeQ2.push(TreeQ1.front()->right);
tmp.push_back(TreeQ1.front()->val);
TreeQ1.pop();
}
if(!TreeQ2.empty()){
ans.push_back(tmp);
tmp.clear();
}
}
return ans;
}
};
[剑指Offer]对称的二叉树
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
if(pRoot==NULL)
{
return true;
}
return issame((*pRoot).left,(*pRoot).right);
}
bool issame(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 issame(left->left,right->right)&&issame(right->left,left->right);
}
};
[剑指Offer]二叉树的下一个节点
/*
struct TreeLinkNode {
int val;
struct TreeLinkNode *left;
struct TreeLinkNode *right;
struct TreeLinkNode *next;
TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
}
};
*/
class Solution {
public:
TreeLinkNode* GetNext(TreeLinkNode* pNode)
{
if(pNode == NULL){
return NULL;
}
if(pNode->right != NULL)
{
pNode = pNode->right;
while(pNode->left != NULL) pNode = pNode->left;
return pNode;
}
while(pNode->next != NULL)
{
if(pNode->next->left == pNode) return pNode->next;
pNode = pNode->next;
}
return NULL;
}
};
[剑指Offer]删除链表中的重复节点
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(pHead == NULL || pHead->next == NULL)
{
return pHead;
}
ListNode *next = pHead->next;
if(pHead->val == next->val)
{
do{
next = next->next;
}while(next != NULL && next->val == pHead->val);
return deleteDuplication(next);
}else {
pHead->next = deleteDuplication(next);
return pHead;
}
}
};